clearfix Reloaded + overflow:hidden Demystified

By YUI TeamSeptember 27, 2010

About the author: Thierry Koblentz is a front-end engineer at Yahoo!
He owns TJK Design and You can follow Thierry on Twitter at @thierrykoblentz

clearfix and overflow:hidden may be the two most popular techniques to clear floats without structural markup.

This short article is about enhancing the first method and shedding some light on the real meaning of the second.


In everything you know about clearfix is wrong I explain the issues this method creates across browsers and I suggest to only use clearfix on elements that are not next to floats (e.g. a modal window), although as authors we still have to deal with collapsing margins. This demo page demonstrates the issue.

Margin-collapse behavior in the first two boxes shows that it is the generated (non-empty) content that keeps the bottom margin inside the box (which makes perfect sense according to spec).

So, to create the same box layout across browsers we can enhance the original method by generating content using both pseudo-elements :before and :after:

.clearfix:after {
  content: ".";    
  display: block;    
  height: 0;    
  overflow: hidden;	
.clearfix:after {clear: both;}
.clearfix {zoom: 1;} /* IE < 8 */

Don't simply replace your clearfix rules with these new ones in existing projects, though, as you may have already patched issues related to collapsing margins via other methods.


In most discussions about clearing floats the overflow:hidden method comes up, and it is always shot down by a "If you're placing absolutely positioned elements inside the div, you’ll be cutting off these elements". But this is not necessary true. overflow:hidden will always clip relatively positioned elements, but it will not always hide absolutely positioned ones. This is because it all depends on the containing block:

10.1 Definition of "containing block":

4. If the element has 'position: absolute', the containing block is established by the nearest ancestor with a 'position' of 'absolute', 'relative' or 'fixed', ...

This means absolutely positioned elements will show outside of a box styled with overflow:hidden unless their containing block is the box itself or an element inside the said box.

You can check this demo page to see how things work.

Better alternatives

If you can apply a width to the element containing floats, then your best option is to use:

display: inline-block;
width: <any explicit value>;

Further reading