As a web developer I frequently will have two floated (child) divs inside of another (parent) div. Actually I do this all day long.
<style type="text/css">
#left {float:left;}
#right {float:right;}
</style>
<div id="parent">
<div id="left" class="child"> </div>
<div id="right" class="child"> </div>
</div>
This doesn’t work without an extra bit of css/html because the parent doesn’t automatically grow to fit floated children. There are two popular ways of overcoming that:
1) Add overflow:hidden to the parent’s css.
2) Add a 3rd “clearing” child <br style="clear:both;" />.
I know there’s a few other similar questions about such things, but my question is:
Which method is better and why? What
are the pros and cons of each?
Hidden overflow – pretty solid method. The main disadvantage is if you set a height on the parent element, any overflow will be…well, hidden. I found this when creating a menu with floated list items – the submenus would not appear.
Clearing element – rather than a line break, I would use a div with
height: 0; clear: both;since it won’t create a gap below. This is a more solid method, the only disadvantage being an extra element in the markup.Float the parent – in my experience there are too many situations where you don’t want to float the parent element, so I would avoid it.
You can also use the generated content method:
This saves the need for an extra element in the markup, but it won’t work in IE7 and below.
Use inline blocks – just remembered this method. Instead of floating the two columns, set them to
display: inline-blockand they will appear side-by-side:Only thing you must remember with this method is if there is any whitespace between the close tag of one block and the opening tag of another, a space will appear between the columns (the size of which depends on the font so it difficult to gauge). As long as you do
...</div><div id=...then this method works fine and is superior to floating elements IMO.