How To Clear Floats The Right Way

When I was working on the template for this very blog I realized that I was still using the lame old <br style="clear:both;" /> way to clear floating elements. You know how we are all lazy and tend to stick to tried and tested methods, especially when our sites have to work properly in a multitude of browsers, but this time, after half a decade of clearbothing I thought enough was enough: It's 2012, there has to be a better way to do all this.

So, I took the time, did a little research and found out that indeed there was a better way, and to top that it's very simple and elegant!

Here's how to do it:

In order to have the containing div extend to the height of the largest child element, simply add the

overflow: auto;

CSS property to the containing div. For extra IE6 pleasure you can also add

zoom: 1;,

not that anyone still using that browser cares about how websites look like. Well, that's it! Hope I'm not the only one who didn't know this.

Enjoyed the post?

Comments (4)

1. jo' paul - 2093 days ago
Here's my nerd reply: Old. QuirksMode posted this method back in 2007. Here's my other reply: Yeah. This is the best way.
2. Ben - 2093 days ago
I've been doing it all wrong! Thanks nice tip.
3. Garth - 2093 days ago
Hey, although it's tempting to do this, there's a risk that this will cause unwanted scrollbars in certain cases so it's inadvisable IMO. This is a good alternative - http://nicolasgallagher.com/micro-clearfix-hack/
4. Sulman - 2093 days ago
Also, you will still need to clear if you wish to have overflow:hidden etc on your element.

Your comment

No HTML allowed. To quote, use [q]text[/q]. Web addresses are automatically converted to links. Please note that comments are moderated and rel="nofollow" is in use. No advertising or link dropping. Don't use keywords or domains as names. Thank you!
Comments are now closed.