Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Center-align a variable-width div in 100% screen

Tags:

css

centering

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?

like image 774
Moe Sweet Avatar asked Nov 04 '11 03:11

Moe Sweet


People also ask

How do I center a div with 100% width?

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.

How do I center a div on all screens?

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.

How do I center align a div in CSS?

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.


2 Answers

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/

like image 89
sandeep Avatar answered Oct 09 '22 14:10

sandeep


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/

like image 33
neric Avatar answered Oct 09 '22 15:10

neric