CSS Clearfix Demystified

| 1 Comment


So you write HTML and CSS. You have a bunch of div’s and you float them all left. You place these floating divs inside a containing div and you expect the container to “wrap” or enclose the floating divs within it. IT DOESN’T! WHY?!?!?

You need to clear the floats first, dummy. See this example to see what we are talking about. Now, we will discuss some techniques to solve this…

Oldschool clear:both

The simplest and most common way to solve this is by adding a BR element with style=”clear:both” inside the container div after your floated divs:

<br style="clear:both" />

And here is a demo of this oldschool technique.

OK cool so it’s working, why change something that ain’t broken? Well, some fundamentalists argue that adding extra HTML markup for layout/positioning is bad and it has a weird smell to it. And I agree to some degree.

Introducing Clearfix

Some clever people then came up with the clearfix CSS technique. This technique allows you to contain flaoting divs without extra structural markup. Basically, this allows you have the same end result as the clear:both example above, but without having to add any additional HTML. Awesome! It was done by using some fancy CSS:

.clearfix:after {
    content: ".";
    display: block;
    height: 0;
    clear: both;
    visibility: hidden;

Check out the demo. There were some limitations to this. Firstly, some older versions of IE do not support it. (Surprise, surprise!) So you need to add some extra CSS for IE and other browsers. 

Quite a bit of people have written about the CSS clearfix technique or had their own take on it. Here are a few articles worth reading:

Micro Clearfix

Then the other day I was browsing the HTML Boilerplate code and noticed some CSS with a link to A new micro clearfix hack. Basically this technique uses the following CSS:

.cf:before, .cf:after { content: ""; display: table; }
.cf:after { clear: both; }
.cf { zoom: 1; }

So all you need to do is add the above CSS to your page and set a class=”cf” on the container div and your’e done. Check out our demo using this technique. There is much less CSS code needed, and it works on all these browsers: Firefox 3.5+, Safari 4+, Chrome, Opera 9+, IE 6+. Sweet! Check out the article.


Stop using additional markup to clear your floats, and start using the micro clearfix today! 


Hi bradvin,

I went throug the examples and there is somthink that does not make sense to me.

I have deleted this:

.clearfix:after { content: "."; display: block; height: 0; clear: both; visibility: hidden; }.

That means that only this is left:

.clearfix {display: inline-block;} /* for IE/Mac */

And the clearfix is still working. Either I must be wrong somewhere or there is a bug in the example.