Clearing floated elements without extra markup
January 16th, 2008 | 0 comments
Clearing floating elements is pretty commonly handled by a a div or br tag with 'clear: both'.
Recently I ran into a problem with this; the layout I was working with was using floats for the sidebar and part of the main content had floated list of images. Using the clear both trick caused it to clear past the bottom of the sidebar.
While there are ways around that I've never been a big fan of adding the clearing divs, so I was pretty happy to find an alternative, and even happier to find one that's nice and simple.
1 2 3 4 |
<ul style="overflow: auto; zoom: 1;"> <li style="float: left">A</li> <li style="float: left">B</li> </ul> |
Basically all you have to do is set the overflow to hidden, which forces the parent to expand to contain all it's children. The zoom: 1 is an IE6 specific property, which is needed to trigger IE's hasLayout.
There are lots of other posts on the topic, if you are feeling like doing some more reading.