Clearing floated elements without extra markup

January 16, 2008

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.

<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 (or auto), 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. A fun trick to avoid any potential hasLayout problems is apply zoom:1 to all div elements, but only for IE (using conditional comments).

Add comment

About

I'm a programmer and shutterbug living on the West Coast of Canada.

Blog Archive

Recently Heard

A Liberal Educationby New Model ArmyPlayed on 2008/07/16 at 02:35PM
The Two Sides of Monsieur Valentineby SpoonPlayed on 2008/07/16 at 02:32PM
You Weren't Thereby New Model ArmyPlayed on 2008/07/16 at 02:28PM
Powered by Viviti