Clear Your Floats - The Right Way

Clear Your Floats - The Right Way

UPDATE

Read http://danott.dev/thoughts/2009/01/06/clear-your-floats-even-easier/ for an even easier way of dealing with floating elements.

Then come back and read this.

Aside from browser bugs, float clearing can be one of the most frustrating aspects of CSS development. It takes a little bit of patience and thought to set up your floats and clears in a way that facilitates both your design and the flexibility required in a modern website.

The Old Way

While judging the last contest of CSS Off , one of the things that I found myself repeating over and over again was this: "Don't use empty divs to clear your floats!" What I meant by that was that in this day and age, there exist much better, more robust, and more semantically correct ways to properly clear floats that simply inserting <div class="clear"></div>.

The Not Really New Way

Enter the EasyClear method . I'm calling this the "Not Really New Way" because it appeared on positioniseverything.net in 2004, but is still being ignored for the old empty clear div solution.

I'm not going to spend time explaining the specifics of why this solution works; they have gone over the technical aspects of the solution in the article, especially different hacks for different browsers. However, before I explain the best way to use the EasyClear on your sites, there is one part of CSS that needs to be understood, since the entire EasyClear method hinges on it: the :after pseudo-element.

:after - Intrigue and Deception

For a long time, I was confused about the :after pseudo-element. After doing a little testing and research, I figured it out. It's not all that difficult to understand, actually, but I was mislead in the beginning. The w3schools.com's definition of :after is the first that pops on on a quick Google search , so it was the first place I went:

The :after pseudo-element inserts some content after an element.

It turns out that this is completely incorrect. The actual definition (via The W3 ) is this (emphasis added):

The ':before' and ':after' pseudo-elements can be used to insert generated content before or after an element's content .

The difference between the two definitions is considerable. Content inserted using the :after pseudo-element is inserted not after the element, but instead within the element and after the content. See an example here .

You can use :after to insert just about any content you'd like, and give it most CSS attributes, including display and clear. This is how EasyClear works its magic.

Using EasyClear

Using EasyClear is simple. The only trick is to apply it to the correct element. The element that you are going to apply it to most is the element containing the floated elements. For example, a page with a container that has a background you'd like to extend to include the entire content, and two floated elements:

Example page

In this example, you want to apply the EasyClear to #container, since that is the containing element. It will insert a block-level element with the clear attribute set to both, thus clearing the floats inside the element without crufting up your HTML. You can see an example at work here , and here's the EasyClear CSS itself:

/* EasyClearing http://www.positioniseverything.net/easyclearing.html */
#container:after {
  content: '.';
  display: block;
  height: 0;
  clear: both;
  visibility: hidden;
}

#container {
  display: inline-block;
}

/* Hides from IE-mac */
* html #container {
  height: 1%;
}

#container {
  display: block;
}
/* End hide from IE-mac */

As you can see, it's pretty simple to employ, and the results are perfect. The best way that I've found to implement this on larger projects is to keep the EasyClear in one place, at the bottom of your main stylesheet, and simply add elements that you need to clear to the declaration itself, as illustrated here .

Clears For All

So now you never have to insert an empty div into your otherwise perfectly crafted HTML. Go read the article , learn the background, spread the word, and, please, just start using it!

Comments (archived for posterity)

  • Mike Robinson commented

    I didn’t know about this, very clever :) Your second position is everything link doesn’t work, though.

  • Dave Woods commented

    The following bit of CSS will also do the same thing and is even easier…

    #container {

    overflow: auto;

    }

    * html #container {

    height: 1%;

    }

  • louis w commented

    I love the clearfix method, it really saves ALOT of headaches and extraneous code. I however would use it more like PIE originally designed and have a .clearfix class then apply it to the div you would like to clear. They way you have it, right inside #container styles would require you to copy it into each item you would like to clear.

  • Dan commented

    @Mike - Thanks for writing in. Fixed that link.

    @Louis - I agree, it’s a fantastic solution. Regarding implementing it, I originally used it like you suggest, adding a “.clearfix” class to each container. But I didn’t like crufting up my HTML, and I usually lean towards not adding class attributes if I can, anyway. So instead, I started adding the specific elements to one declaration. I have an example set up here.

  • Mohamed Jama commented

    I’ve enjoyed reading your post, but I always wonder why would you need to clear anything to start with? if you float your parent element and then float everything under it your code won’t need to be cleared

    /** main div **/

    /** div 1 **/

    /*** div 2 **/

    this way you won’t need to clear anything.

    Regardless thanks for the interesting read

  • Mohamed Jama commented

    ^^^^ Ooops well I forgot you could use tags here :( , it didn’t show my example

  • Dan commented

    @Mohamed - In decent browsers, you’ll see that if you don’t clear your floats, the parent element will not stretch to include all of it’s children. I’ve set up an example of that here so that you can see what I’m talking about. You can’t just rely on simply setting heights of elements, because that will break down when people start resizing text, so much of the time, you’ll need to use some sort of clearing method.

  • Dan commented

    @Dave - That does indeed work for this example, but there are other times when you’d need to clear a float where the overflow:auto solution would be cumbersome, or, perhaps you need overflow for something else. Either way, they’re both strong solutions to keep in your toolbox.

  • Mohamed Jama commented

    hey Dan,

    try this

    #container{ background: #79aff2; padding: 10px; border:1px solid #1b5fab;float:left;}

    #container #float1{ float:left; background: #eddd94; padding: 5px; border:1px solid #333; margin: 5px; width:300px;}

    #container #float2{ float:left; background: #eddd94; padding: 5px; border:1px solid #333; margin: 5px; width:300px;;}

    it works fine without setting the height, this is just my opinion though Dan :D

  • Dave Woods commented

    Hi Dan,

    I think Mohamed was talking about floating the parent container and applying a width so that it would stretch to contain its children. Whilst that method works, sometimes it can cause issues especially when dealing with fluid layouts where a percentage is required so I would suggest clearing where possible otherwise you’ll end up needing to float all elements which can lead to a lot of extra CSS.

    I can’t think of any situation where the overflow method would be cumbersome? All the overflow: auto; method does is remind the parent that it should be set to auto anyway and forces it to contain its children. If you needed to use overflow for another purpose then you should find that overflow: hidden or scroll; work just as well ;)

    Thanks

    Dave

  • Mohamed Jama commented

    Hey Dave,

    Yeah it might include a little more CSS but then again you don’t actually need to apply width to the parent DIV and yeah you are correct you have to float all elements within that parent. It worked for and is tuck with it to be honest, I will give the easyclear a chance as soon as i can though

  • Dan commented

    Dave -

    You’re right; they’re both valid solutions to the same problem. It’s a win either way, since you’re removing the need for non-semantic content like empty divs.

    Also, you get points in my book for using “whilst” (:

  • Will Wilkins commented

    Hi Dan, Interesting method. However, the last method shown by Mohamed should work fine as well. However, the width of the container would have to be set to span the page as it did before the float. But Mohamed could have kept the styling within the #container div and he set both of the ‘float’ containers to the same width.

  • Terrence Wood commented

    overflow:hidden is the better option for containing floats, it prevents FireFox from giving the clearing element focus when tabbing through a page and prevents scrollbars appearing where the clearing element shrinkwraps an anchor. Again, you must ensure that the containing element hasLayout for it to work in IE6. hasLayout is triggered by setting an explicit width amongst other things.

    @Mohamed Jama, one situation where you wouldn’t want to use float to clear other floats is when you want to add margin: auto to the container.

  • Steve commented

    I use this method to clear my floats all the time. To me, it’s the best solution out there. Thanks for posting this. Cheers. =)

  • Nacho commented

    Great help. I used empty divs. But not anymore.

    Thank you :]

  • Andreas Lagerkvist commented

    I’ve used easy clear for as long as i can remember but the overflow-one seems fine as well. I remember hearing it doesn’t always work in IE though?

    I agree that you shouldn’t add .clearfix-classes all over the place as they are completely design-related. I use my css-constants to avoid having to use a class but still be able to structure my CSS any way i want:

    #navigation ul = $self-clear;

    other code

    #wrapper = $self-clear;

    etc…

  • Zed commented

    #container {

    overflow: auto;

    }

    * html #container {

    height: 1%; }

    And how do you remove/hide the scrollbar that is displayed from de overflow:auto?

  • Ian van den Heuvel commented

    I found a MUCH easier method to clear floats a while back. While it’s sort of related to other methods posted in the comments, the beauty lies in its simplicity. No IE hacks, one simple declaration. Only a single drawback that I’m aware of. And it works across all major browsers.

    Using your example, Dan:

    
    #float1, #float2 {
    
      float: left;
    
      clear: none;
    
    
    }
    
    
    #container {
    
      overflow: hidden;
    
    }
    
                  

    As we all know, IE6’s incorrect handling of floats, will be used against itself in this elegant solution - it does by default what you need it to. The drawback I mentioned is, of course, that you cannot set the height for #container.

  • Travis Miller commented

    ...except this technique doesn’t work in IE6 or IE7, and is therefore useless for real-world production work.

  • Miel commented

    Hello,

    for some time i used the clearfix method too but there was a twist on this method!

    Everytime i used this method (a div wrapper with 2 containing div’s, one floating left and the other floating right) on the bottom of my wrapper there was some open space, like i used a margin-bottom om my wrapper. ATTENTION: you can see this when your wrapper is larger then your windowscreen, you can scroll down to the bottom of your site and see it.

    Now i found the SOLUTION to this method, just place the code font-size: 0; into your class, like bollow:

    
    
    
    /*================================================
    
      C L E A R F I X
    
    ================================================*/
    
    
    .clearfix:after {
    
      content: “.”;
    
      display: block;
    
      height: 0;
    
      clear: both;
    
      visibility: hidden;
    
      font-size: 0;
    
    }
    
    .clearfix {display: inline-block;}
    
    /* Hides from IE-mac *
    
    * html .clearfix {height: 1%;}
    
    
    .clearfix {display: block;}
    
    
    /* End hide from IE-mac */
    
                

    and IT WORKS very well :)

  • Vince commented

    Whats the big deal if someone does use a div with class=clear? Its not going to slow the browser loading time, it doesn’t look ugly and it doesn’t affect performance.

    BIG DEAL!

  • Kev commented

    Why not just use a at the end of your containing div, it’s more semantic….

  • Kev commented

    the BR html was cut off from the comment above, <br class=“clear” >

  • Dan commented

    @Dave / all readers - In the time between your comment here and now, I’ve seen the light. Read http://danott.dev/thoughts/2009/01/06/clear-your-floats-even-easier/

    @Vince and @Kev - I am not a fan of non-semantic elements floating around in my HTML. It makes the code harder to maintain, and uglier to look at. Do some reading on the topic for a more in-depth explanation. Plus, with this new technique, it only takes <strike>one</strike> two (damn ie6) lines of CSS. It’s all upside.

  • Maak Bow commented

    What’s wrong with clearing floats without any of this complexity simply by adding {overflow:auto;{ to the container that does not expand to contain the floats?

    Its simple

    It works