Center block element in element

I’m trying to center a block element (the WordPress caption box, including the image) but it won’t work. I’ve tried:

.imagecenter {
   margin-left: auto;
   margin-right: auto;
   display: block;
}

But it just won’t work. I’ve also tried margin-left: auto; margin-right: auto; but that won’t work either. Is there anything I’m doing wrong? This is what the W3C documentation says I should do.

Read More

It looks like this in the HTML (to clarify):

<div id="content">
........post here......
<div class="wpcaption imagecenter" style="width:225px">
<img src="blah" />
Blah.
</div>
.........post here......
</div>

I have no control over the width of the element. It’s set by the user. The user wants the div to be centered. It’s not working. I’ve looked over documentation but it still won’t work.

EDIT: I HAVE ALREADY TRIED MARGIN-LEFT: AUTO AND MARGIN-RIGHT: AUTO. IT DOESN’T WORK.

Related posts

Leave a Reply

4 comments

  1. In general, to position a div in the center, the technique is to make both the left and right margins auto and then give the div a width:

    .centerDiv
    {
        margin-left:auto;
        margin-right:auto;
        width: XXX px;
    }
    
  2. Give it a width less than that of its parent.

    .parent    { }
    .imgCenter { width:320px!important; margin:auto; }
    
    <div class="parent">
      <img src="foobar.jpg" class="imgCenter" />
    </div>
    
  3. An easier solution might be to set margin-left: auto, margin-right: auto and text-align: center (for the caption text) on all child elements of your containing element:

    .imagecenter *{
        margin-left: auto;
        margin-right: auto;
        text-align: center;
    }
    

    This means you won’t have to explicitly set the width of your containing element, but has the drawback that your caption text will have a 100% width, which might look wierd.

  4. I know this is an old question, but for those of who find this on Google, I found another answer:

    Just give these attributes to your wrapper element and the contents will be center aligned.

    width: 1024px; 
    margin-left: auto;
    /* I have used 1024px since I set the minimum resolution requirements for my website as 1024 x 768 */