Web Standards Tips

Practical advice for building websites with web standards

Easy clearing of floats

By Isofarro on November 18th, 2008 - 2 comments

One of the main methods of creating stable layouts is to ensure that elements that contain floated elements clear these floats.

Given an element with an id of wrapper, the styles needed to easy clear any contained floats is:

#wrapper:after {
	content: ".";
	display: block;
	height: 0;
	clear: both;
	visibility: hidden;
#wrapper {
	zoom: 1;

The :after selector deals with most modern browsers, so Firefox, Safari, Opera (the ones listed as Grade A browsers in Yahoo!’s Graded Browser Support chart). Internet Explorer 6 and 7 ignore this rule, so the second stylerule, the zoom: 1 triggers hasLayout in IE6 and 7 which does the self-clearing of floats.

If valid CSS is an absolute and non-negotiable requirement, then zoom: 1 is going to be a problem. So instead you could replace the zoom:1 selector rule with another style-rule that triggers hasLayout in IE, like height: 0%, or overflow: hidden – pick your poison.

2 Responses to “Easy clearing of floats”

  1. I prefer the following approach:

    #wrapper {
       overflow: hidden;
       _zoom: 1

    Of course, this only works on elements that don’t have an explicit height, but is decidedly less fiddly. What’s more, the above actually *contains* the float, rather than clears it, so you can style #wrapper with the full knowledge that it’ll contain its floated children.

    The problem with the :after fix is that designs tend to have a lot of elements that need clearing. One option to deal with this is to duplicate this fix multiple times for each element that needs to be cleared, resulting in CSS bloat. Alternatively, you could use a generic class selector (i.e. ‘clearfix‘) and apply that class to all the elements that need to be cleared, but that pollutes the markup with stylistic class names.

    The above approach is short enough to be repeated multiple times and not make the CSS file unreadable. You do have to add a comment to make sure that other developers know what you’re doing, though.

  2. Steve, overflow: hidden is an excellent alternative for the reasons you cover. Thanks.

    One pitfall or gotcha you need to watch out for using overflow: hidden is that elements inside that container that are positioned absolutely and need to spill outside that container (like a JavaScript powered drop-down menu near the bottom of the container) get truncated/clipped to the overflow: hidden styled container. It won’t appear outside of the container at all because of the overflow: hidden.

    Other values of overflow cater for this by applying scrollbars to the container, so the design goes right out of the window.

    Still, if absolutely positioned child elements are not needed, overflow: hidden is a great alternative to the content:after self-clearing method.

Add a comment or reply

Copyright © 2007 - 2009, isolani