The very latest new new way to do "clearfix"

This article was first published on CSS-101 (07-01-2012).

Who would think there is still something to write about clearfix? 🙂

“clearfix” for modern browsers

Two years ago, I wrote clearfix Reloaded + overflow:hidden Demystified, where I proposed an addition to the original clearfix rules in the form of the ::before pseudo-element, to prevent collapsing margins in modern browsers.

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

It was a fix that fixed the fix. This is because the use of hasLayout for IE 6 and 7 made these browsers contain margins, something modern browsers did not do.

Nicolas Gallagher improved on this by using an empty string with display:table, he called the new technique the new micro clearfix hack. Nicholas noted that with the upcoming new Firefox versions, it was safe to go a shorter route.

/**
 *  For modern browsers
 */
.cf:before,
.cf:after {
    content:"";
    display:table;
}
.cf:after {
    clear:both;
}
/**
 * For IE 6/7 (trigger hasLayout)
 */
.cf {
    *zoom:1;
}

Today, along the same lines, I believe most of us can simply rely on a single rule:

.btcf:after {
    content:"";
    display:table;
    clear:both;
}

Why is that?

No need for zoom:
If you don’t support IE6 and 7, then don’t bother clearing floats in these browsers. And if you use * { box-sizing: border-box } you have even less reason to include zoom in any of your styles sheets.
No need for ::before
We did not use ::before for years. The only reason to add this selector was to achieve better cross browser rendering. So if we drop zoom, we can safely drop ::before as well.

A word of caution: if you start a new project from scratch, go for it, but don’t swap this technique with the one you have now, because even though you do not support oldIE, your existing rules prevent collapsing margins.

For those wondering about the class name… It stands for Beat That ClearFix! 🙂