Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

centering div of unknown width inside a div

Tags:

html

css

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.

like image 721
frenchie Avatar asked Dec 11 '25 17:12

frenchie


2 Answers

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.

like image 76
Roddy of the Frozen Peas Avatar answered Dec 14 '25 09:12

Roddy of the Frozen Peas


This may not technically be the right way of doing it, but you could put text-align:center on your wrapper div.

like image 45
Travesty3 Avatar answered Dec 14 '25 10:12

Travesty3



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!