Clearing Floats: An Overview of Different clearfix Methods

Tweet

Clearing floats has long been a common necessity in front-end development. It’s no surprise then that over the years, we’ve been exposed to multiple methods for clearing floats, nowadays more commonly known as “clearfix methods”. Before we dig into the various methods, let’s take a look at the problem that clearfix methods attempt to solve.

The scenario: .el-1 and .el-2 are floated side by side inside a .container element, and there’s a .main element after .container.

The desired outcome: We want .container to expand to the height of its child elements (i.e. the taller of either .el-1 or .el-2), and we want .main to be after .container.

The actual outcome: .container collapses and takes on no height at all, as if there is nothing inside it, putting .main in an undesired location and potentially causing any backgrounds or borders on .container to be missing.

Based on the above scenario, our markup may look something like this:

<div class="container">
  <div class="el-1">A long string of stuff here...</div>
  <div class="el-2">A short string of stuff here...</div>
</div>
<div class="main">
  Some stuff here...
</div>

Then our CSS may look something like this:

.el-1, .el-2 {
  float: left;
  width: 50%;
}

.el-1 {
  /* styles for .el-1 here */
}

.el-2 {
  /* styles for .el-2 here */
}

.main {
  /* styles for .main here */
}

Finally, the result is as shown in this demo:

See the Pen Why we need to clear floats by SitePoint (@SitePoint) on CodePen.

By looking at the demo and examining the CSS for the .container element, you’ll see that it is indeed collapsed. You can see a hint of a black border at the top, and there is no sign of the background color. So it doesn’t expand to contain .el-1 and .el-2, thus leaving .main to jump up to an awkward spot (underneath .el-2 in our case).

Contrary to what many might think, this is not a browser bug, or an improper implementation of floats. This is simply how floats work. A lot of times in our development though, this is not our desired outcome. Which brings us to the simple task of having to “clear floats”.

Clearing floats (or clearfixing) basically forces the containing element to expand to contain its child elements. It thus forces the subsequent elements to appear below it. Over the years, many methods have been explored to clear floats. Before we look at these methods, however, let’s first examine the CSS’s clear property, which is one of the primary CSS features we’ll use to help us solve this problem.

The “clear” Property

MDN defines clear like this:

The clear CSS property specifies whether an element can be next to floating elements that precede it or must be moved down (cleared) below them.

From this definition alone, it’s clear why the clear property can clearly clear our floats…right. Now, let’s dig into some methods.

Solution 1: The Old School Way

This method is old school. Old school is relative, and of course the real old school method involves the use of tables for layout (in which case clearing floats means nothing). So consider this method old school as far as the existence of floats goes.

The idea is simple: Insert an empty element that has the clear property declared on it at the bottom of the container of floated elements. It’s long been tradition to use a specific class to achieve this, so that you can reuse it in your HTML. Here’s the classic CSS structure:

.clear {
  clear: both;
}

And the HTML might look like this:

<div class="container">
  <div class="el-1">I'm floated...</div>
  <div class="el-2">I'm also floated...</div>
  <br class="clear">
</div>

<div class="main">
  Bravo, sirs and madams. I'm in the clear.
</div>

And here is our demo with this method implemented:

See the Pen Old school float clearing by SitePoint (@SitePoint) on CodePen.

Note: If you don’t care about the collapsed container, and only about the mis-positioned .main element, then you could also choose to place the “cleared” element after the container. But if you choose to do that, then you might as well just put the clear: both declaration on the .main element itself.

This method was the go to method once upon a time. It works, plain and simple. However, in these modern times of separating content from style, and trying to keep things as semantic as possible, this method is generally frowned upon by many.

Method 2: The Overflow Way

Using the overflow property on our .container, we can actually force the container to expand to the height of the floated elements. Our CSS will look like this:

.container {
  overflow: hidden; /* can also be "auto" */
}

And our HTML would remain as it was originally, with no extra elements.

Here’s the demo:

See the Pen overflow: hidden/auto float clearing by SitePoint (@SitePoint) on CodePen.

As you can see, our .container expands to the height of our floated elements, background colours, borders, and background images will fill it up if applied, and all is well.

However, one of the main drawbacks of this method is the fact that any child content that pokes outside the container element is going to either get clipped (assuming a value of hidden) or is going to cause scrollbars to appear (assuming a value of auto). Better than our previous solution, but still far from ideal. Let’s dig further.

Method 3: The “clearfix” Class

You hear about it often, but what is it? All the cool kids are using it, and you want to also. The “clearfix” (which means fixing the clearing of floats) defines a .clearfix class in our stylesheet that we can apply to any float-containing element. This will force the container element to expand, pushing subsequent elements beneath it. How does it work? It uses the awesome CSS pseudo-elements ::before and ::after. Nicolas Gallagher describes it pretty neatly:

This … generates pseudo-elements and sets their display to table. This creates an anonymous table-cell … The :after pseudo-element is used to clear the floats. As a result … the total amount of code needed is reduced.

The CSS looks like this:

.clearfix:before,
.clearfix:after {
  content: "";
  display: table;
}

.clearfix:after {
  clear: both;
}

.clearfix {
  zoom: 1; /* ie 6/7 */
}

And our HTML would be modifed slightly to look like this:

<div class="container clearfix">
  <div class="el-1">I'm floated...</div>
  <div class="el-2">I'm also floated...</div>
</div>

<div class="main">
  Bravo, sirs and madams. I'm in the clear.
</div>

And here is our demo once again with the clearfix added:

See the Pen Float clearing with micro clearfix by SitePoint (@SitePoint) on CodePen.

And take note that Chris Coyier advises that if you don’t need to support anything below IE8, you could get by with just the following:

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

Simple, effective, semantic, and easily reusable.

Note: The method used above is the “micro clearfix”, as popularized by Nicolas Gallagher. The only difference is the class name that Nicolas uses. Previous to that method, there were similar techniques as described by Peter-Paul Koch and Thierry Koblentz. Basically, the clearfix has a pretty long history and the method we’re using above is the latest iteration.

Method 4: The Future contain-floats Value

Interestingly, the W3C specification has added a new value to the min-height property (and to other min/max properties), in order to help solve this problem. It looks like this:

.container {
  min-height: contain-floats;
}

This basically will do the same thing as the clearfix or the overflow method, but with a single line of code and without any of the drawbacks we’ve discussed. And of course, you could create a separate reusable clearfix class that this could be attached to, and just use it once in your CSS.

It doesn’t appear that any browser supports this value as of yet, but it’s certainly something to keep an eye on.

Wrap Up

And there you have it, folks, a quick run-through of various “clearfix” methods. The application of the .clearfix class has become the standard, and I highly recommend using that instead of the previous two methods. It just makes life easier. Of course, whatever works best for you will always do the trick, but, as mentioned, I’d advise staying away from method 1 these days and sticking for the most part to the standard clearfix hack.

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • James Donaldson

    There’s also the “float the container” solution. Like overflow: hidden, it has the drawback of potential side-effects you may not want, but it works great if floating the container doesn’t break your layout scheme.

  • Gemma W.

    Another alternative is to give .container a height.

    • callmenick1

      This would mean height-restricting your content though, no? Unless you were absolutely certain that the content of your floated elements never crossed that height. Risky business I think.

  • http://wordpressinurdu.com/ Tahir Taous

    Empty Div method is also an option but not recommended.

  • Philip C

    Thank’s, this has cleared my mind :)

    • callmenick1

      Haha, clever.

      • Philip C

        Honestly though, this is a really helpful article for my work. And, I don’t think you could have made it more clear. :)

        • callmenick1

          Thank you. Kudos to Louis Lazaris and the Site Point team for their guidance and opportunity to let me write for them.

  • callmenick1

    Yeah, I find the clearfix class is just the easiest to remember and implement. You don’t have to keep toggling back to your CSS.

  • Pumbaa

    Excellent article, Nick. Hoping to see more articles from you on Sitepoint :)

    • callmenick1

      Thank you!

  • http://sebastianstoll.dk/ Sebastian Stoll

    No width:100%;float:left; ?????

    • LouisLazaris

      Too many drawbacks to that solution, but yeah, technically that would work in some cases.

  • Ralph Mason

    There are other methods that can come in handy on occasions, such as setting the container to display: table, or to position: absolute ( yeah, I know, not that useful, but …), or you could use display: inline-block instead of floating, though that’s technically off topic, as is display: flex …

    • callmenick1

      True, all valid points, although this article is to discuss clearfix methods in particular (as opposed to floating alternatives).

      • Ralph Mason

        Yep. The first two I mentioned are clearfix methods for when floating is used. Both display: table and position: absolute on the container cause it to wrap floats.

        • LouisLazaris

          That’s interesting because yeah, technically, it does seem to contain the floats, as seen here:

          http://jsbin.com/denud/1/edit

          But it has waaaayyy too many drawbacks to consider as a valid option. Positioning it absolutely takes it out of the normal flow, so now the elements after it (the “main” and link) are not appearing behind it. So it kind of defeats the purpose.

          • Ralph Mason

            Yes, the position: absolute method is rarely useful, unless, say, you have a small container that is already positioned absolutely, and has a few floated children—which I have seen once (and I guess might be relevant in a megamenu scenario etc.). All it would mean is that you don’t need any kind of clearfix on the container. Worth knowing about, anyhow. For mine, the display: table method is more useful; though, to be honest, I use overflow: hidden 99% of the time.

  • callmenick1

    box-sizing: border-box
    ;)

  • callmenick1

    As mentioned in the article, the empty element was an old school way that is now frowned upon. Even though it works, I don’t suggest using it!

  • Kuldeep Sharma

    I use a .clear class with clear:both and overflow:hidden, and it seems to work very well. Sometimes, skipping the overflow part makes some difference on the layout so I use it together.

  • Laurence Hughes

    That works in terms of putting #main in the right position, but this approach has two drawbacks.
    Firstly, it’s inflexible. It only fixes things for #main. What if your client has a CMS and adds #client-element after .container? Then the layout for #client-element would be broken. So it’s more modular and flexible to apply the clearfix to .container since this fixes layout for *any* possible element following .container.
    Secondly, if you wanted to put a bottom-border style on #container, this wouldn’t work unless you apply a clearfix method to .container which forces it to properly contain its inner elements.

  • ashleyjetjaden

    Wahoo! Method 3 fixed my problem instantly… thanks a million!

  • Dustin

    I prefer a clearing div. It always works.