I got this HTML
<div id="wrapper">
<div id="center">
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
<div class="clearBoth"></div>
</div>
</div>
And CSS
#wrapper{width:100%}
.cell{float:left}
So wrapper is 100% width and the width and number of cells are variable, meaning width of #center is variable too.
Question: How do I keep #center horizontally center-aligned?
Set the width of the outer element (i.e. 100% covers the whole line). Change it according to your requirements. Set the margin property to "auto" to horizontally center the <div> element within the page. The "margin: 0 auto" does the actual centering.
With CSS, you can center text in a div in multiple ways. The most common way is to use the text-align property to center text horizontally. Another way is to use the line-height and vertical-align properties. The final way exclusively applies to flex items and requires the justify-content and align-items properties.
Center Align Elements To horizontally center a block element (like <div>), use margin: auto; Setting the width of the element will prevent it from stretching out to the edges of its container.
Yes you can do it with display:inline-block
.
For example:
css:
#wrapper{
width:100%;
text-align:center;
}
#center{
display:inline-block;
*display:inline;/* IE*/
*zoom:1;/* IE*/
background:yellow;
overflow:hidden;
text-align:left;
}
.cell{
float:left;
width:50px;
height:50px;
background:red;
margin:5px;
}
Check this example http://jsfiddle.net/8a4NK/
Revisiting this in 2017
#wrapper{
width:100%;
display: flex;
justify-content: space-around;
}
#center{
background:yellow;
display: flex;
}
.cell{
width:50px;
height:50px;
background:red;
margin:5px;
}
Fidle: http://jsfiddle.net/027m8mnv/
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