Over and over again at places I've worked, I've noticed other web developers struggle with clearing floats in CSS. I've seen all sorts of unique solutions to the problem, many which frighten me. I've seen solutions using JavaScript, some using obscure CSS properties such as the .clearfix class introduced at P.I.E. and others just setting a fixed height on elements.

Common HTML Setup For A CSS Layout

The HTML below is a pretty standard setup for most websites. Generally people want the #footer DIV to fall below the #container DIV. Also many people will want the background-color of the #container DIV to be solid and touch up against the #footer DIV.

<div id="container"> <div id="floatleft"> <p>Float Left</p> <p>Float Left</p> <p>Float Left</p> <p>Float Left</p> <p>Float Left</p> <p>Float Left</p> </div> <div id="floatright"> <p>Float Right</p> <p>Float Right</p> <p>Float Right</p> <p>Float Right</p> <p>Float Right</p> <p>Float Right</p> </div> </div> <div id="footer">Footer Div</div>

Now view how this HTML renders with the basic CSS applied to it > >

Solution #1: Giving The #container DIV a Height

Notice how the #footer DIV is much too high and doesn't clear the #container or it's two child DIVs? The most common fix to this problem that I've seen is to give the #container DIV a height like so:

height: 232px;

View This In Action >>

At this point most web developers would just move on to the next project and consider this finished. The problem is, when the height changes or receives more content this design is broken.

Solution #2: Clearing Float Using clear: both;

The next common fix to this is to use clear: both; on the #footer DIV:

#footer { clear: both; }

View This In Action >>

While this does actually clear the #footer DIV notice how the yellow bordered #container DIV is still a small sliver at the top? If you used a repeating background-image or background-color this solution would not work.

Finally, a New Way To Clear Floats

There's a seldom used CSS property called "overflow" which will fix this problem for us. The W3C describes the overflow property as a property that specifies whether content of a block-level element is clipped when it overflows the element's box. It affects the clipping of all of the element's content except any descendant elements (and their respective content and descendants) whose containing block is the viewport or an ancestor of the element.

In common english that means that if a container has floated or absolute positioned elements it will not have a height. In order for it to "expand" to the size of it's floated children the CSS overflow property must be set, in this case to "auto"

overflow: auto;

View This In Action >>

Voila! The #container DIV now assumes the variable height of it's floated children and the #footer DIV clears the #container DIV.