Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Horizontally centering elements inside a div

To make this easy, say you had a div that was 100px wide, and 3 divs inside of it each 20px wide. How can I align them to where they align to the center of the div leaving a 20px; gap on each side?

like image 487
Optiq Avatar asked Aug 08 '26 02:08

Optiq


1 Answers

Center some HTML elements always depends of your project and integration dependencies...

You may be happy with these 2 solutions, display: inline-block; and float: left;

Both have pros & cons, hope that it can help you !

http://jsfiddle.net/HP2DS/1/

<!-- Inline-block -->
<div id='container'>
    <div class='centered' id='content-left'></div><div class='centered' id='content-center'></div><div class='centered' id='content-right'></div>
</div>

#container {
    width: 100px;
    height: 80px;
    text-align: center;
    background: cyan;
}

#container .centered {
    display: inline-block;
    width: 20px;
    height: 100%;
    margin: auto;
    background: magenta;
    border: 1px solid black;
    box-sizing: border-box;
}

<!-- Floating -->
<div id='container-2'>
    <div class='centered' id='content-2-left'></div>
    <div class='centered' id='content-2-center'></div>
    <div class='centered' id='content-2-right'></div>
</div>

#container-2 {
    width: 60px; /* 60px + 2*20px of padding... */
    height: 80px;
    padding: 0 20px;
    text-align: center;
    background: cyan;
}

#container-2 .centered {
    float: left;
    width: 20px;
    height: 100%;
    margin: auto;
    background: magenta;
    border: 1px solid black;
    box-sizing: border-box;
}
like image 184
Flo Schild Avatar answered Aug 09 '26 15:08

Flo Schild



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!