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 .InnerGreen to act as inline-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:
#Wrapper {
text-align: center;
}
See updated JSFiddle.
This may not technically be the right way of doing it, but you could put text-align:center on your wrapper div.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With