I have a wrapper div element that contains a div that in turns contains divs inside; these divs are added or removed at runtime. The HTML and CSS look like this:
<div id="Wrapper">
<div class="InnerGreen">
<div class="InnerContent"></div>
<div class="InnerContent"></div>
</div>
</div>
#Wrapper{
width:600px;
height:50px;
margin:10px 20px;
background:blue;}
.InnerGreen{
background:green;
margin:10px auto; // this doesn't center
overflow:hidden;
display:inline-block;}
.InnerContent{
background:yellow;
height:30px;
width:40px;
float:left;
margin:3px 5px;}
I’m using inline-block to wrap the .InnerGreen inside the Wrapper; however, the margin:auto don’t seem to horizontally center the div. Of course, this works if I define the width of .InnerGreen but in reality, the .InnerContent divs are a collection of divs of all different sizes so I can’t set the width of .InnerGreen at runtime.
How can I make the margin:auto work? Here the the jsfiddle.
Thanks for your suggestions.
Inline elements have no margins. By telling
.InnerGreento act asinline-block, you’re essentially telling it to act as inline with regards to positioning. On the other hand, you can still center it using text-align:See updated JSFiddle.