I want to know if there exists an elegant way to horizontally align 3 divs
without using float
css property.
HTML:
<div id="parent">
<div id="first">Left</div>
<div id="second">Middle</div>
<div id="third">Right</div>
</div>
I ask this question because the parent div
has not float
property and adding float
to children cause problems on page resizing.
To center a div horizontally on a page, simply set the width of the element and the margin property to auto. That way, the div will take up whatever width is specified in the CSS and the browser will ensure the remaining space is split equally between the two margins.
(You'll see why in a bit.) To position the divs side by side, we are using the float property to float each . float-child element to the left. Since they are both floating to the left, they will display side by side if there's enough space for both to fit.
You can use display:inline-block
or display:table-cell
with the inner content.
#parent{ display:flex; justify-content: space-between; }
JSFiddle
#parent{ display:table; width:100%; }
#parent div{ display:table-cell; }
#first{ text-align:left; }
#second{ text-align:center; }
#third{ text-align:right; }
JSFiddle
#parent{ width:100%; white-space:nowrap; }
#parent div{ display:inline-block; width:33.3%;}
#first{ text-align:left; }
#second{ text-align:center; }
#third{ text-align:right; }
JSFiddle
Adding to notulysses's answer, If ancient browser support is not an issue, you can use css3 Flexible_boxes.
By applying display:flex
the child divs will be aligned horizontally (by default)
#parent{
display:flex;
justify-content:space-around;
}
more about flexbox @ CSSTricks
This will avoid the white space issue with inline-block
elements
JSfiddle
Instead of finding a workaround for floating, you could also use the following fix for your "resizing problems" (at least what I think it is caused by):
After using floats, you should always clear your floats. You can do this by adding an extra <div>
with a class.
<div id="parent">
<div id="first">Left</div>
<div id="second">Middle</div>
<div id="third">Right</div>
<div class="clear"></div>
</div>
In CSS:
.clear{
clear: both;
}
#parent {
display: table;
}
#first, #second, #third {
display: table-cell;
}
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