the clearfix hack

Here is a weird, bad thing that can sometimes happen when using floats:

img {
float: right;
}
<div>An Image

Uh oh... this image is taller than the element containing it, and it's floated, so it's overflowing outside of its container!

Boo. There is a way to fix this, but it's ugly. It's called the clearfix hack.

Let's try adding this new CSS:

.clearfix {
overflow: auto;
}

Now let's see what happens:

<div class="clearfix">An Image

Much better!

This works for modern browsers. If you want to support IE6 you will want to add the following:

.clearfix {
overflow: auto;
zoom: 1;
}

There are exotic browsers that may require extra attention. The world of clearfixing is pretty scary, but this simple solution will work for the vast majority of browsers today.

12 / 20
  • Creative Commons License