Center block element in element
Solution 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;
}
Solution 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>
Brandon Wang
Most of my questions/answers were 2010-2013, when I was < 14 years old — so please, some grace if the questions seem too basic!
Updated on June 09, 2022Comments
-
Brandon Wang almost 2 years
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.