Patrick Ward words, code, and music

Techniques to Clear Floats in CSS

I ran into the pervavise issue of having to clear a DIV that contains only floated DIV elements in it recently. The problem is that the outer container does not stretch to accomodate the height of it’s child containers. So, if you have a background or a border on the containing element, it does not fully cover the child elements.

It’s an old issue, but I keep forgetting where to find the information on how to fix it. So, this is a note to self for future reference.

I found the following resources to be the most useful in terms of the pros and cons of each technique. Please see them for more detailed instruction. I’ve summarized the basics below.

Add an Empty DIV and clear:both Styling

The easiest, and oldest, fix is to add an empty DIV with a style of clear:both to the end of the outer container. This works, but it’s not semantic and makes a mess of the page’s markup.

#container { border 1px solid #000000; }
#left   { width: 45%; float: left; }
#right  { width: 45%; float: right; }
.clear { clear:both; }
<div id="container">
  <div id="left">Lorem ipsum...</div>
  <div id="right">Lorem ipsum...</div>
  <div class="clear"></div>
</div>

Use the clearfix Hack

Beyond adding additional markup to the page, you can use the infamous ‘clearfix’ hack, which cheats by adding additional content after the containing element. While this prevents you from having to muddy the markup on the page, it feels a bid hackish to me.

/* This fixes the problem for most browsers */
.clearfix:after
{
  content: ".";
  display: block;
  height: 0;
  clear: both;
  visibility: hidden;
}

/* This fixes the problem for IE7 */
.clearfix { min-height: 1%; }

/* This fixes the problem for IE6 */
* html .clearfix { height: 1%; }

Use the overflow:hidden Technique

The method I’ve tended to use and that has the least problems in my experience is the overflow method, with some additional css to trigger hasLayout in IE.

This method works great as long as there is no fixed height on the outer container. See Quirksmode for ways to resolve issues related to this technique.

I’ve seen some references indicate that you can use overflow:auto to achieve the same results, but you risk having scrollbars show. So far, the overflow:hidden method has been the cleanest and most efficient technique for me.

/* Cleanest method */
.container {
  overflow: hidden;
  display: inline-block; /* Necessary to trigger "hasLayout" in IE */
  display: block; /* Sets element back to block */
}
/* Or, use the zoom method to trigger "hasLayout" in IE */
.container {
  overflow: hidden;
  zoom: 1; /* Necessary to trigger "hasLayout" in IE */
  display: block; /* Sets element back to block */
}