Center block element in element

2019-03-28 09:34发布

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.

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.

4条回答
孤傲高冷的网名
2楼-- · 2019-03-28 10:02

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.

查看更多
女痞
3楼-- · 2019-03-28 10:22

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;
}
查看更多
来,给爷笑一个
4楼-- · 2019-03-28 10:27

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>
查看更多
贪生不怕死
5楼-- · 2019-03-28 10:27

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 */
查看更多
登录 后发表回答