Spring Sale! Save 30% on all books w/ code: PLANET24
Web Dev + WordPress + Security

The New Clearfix Method

Say goodbye to the age-old clearfix hack and hello to the new and improved clearfix method..

The clearfix hack, or “easy-clearing” hack, is a useful method of clearing floats. I have written previously about the original clearfix method and even suggested a few improvements. The original clearfix hack works great, but the browsers that it targets are either obsolete or well on their way. Specifically, Internet Explorer 5 for Mac is now history, so there is no reason to bother with it when using the clearfix method of clearing floats.

The original clearfix hack looks something like this:

.clearfix:after {
	visibility: hidden;
	display: block;
	font-size: 0;
	content: " ";
	clear: both;
	height: 0;
	}
.clearfix { display: inline-table; }
/* Hides from IE-mac \*/
* html .clearfix { height: 1%; }
.clearfix { display: block; }
/* End hide from IE-mac */

Yes it’s ugly, but it works very well, enabling designers to clear floats without hiding overflow and setting a width or floating (nearly) everything to get the job done. The logic behind this hack goes something like this:

  • Target compliant browsers with the first declaration block (if all browsers were standards-compliant, this would be the only thing needed) and create a hidden clearing block after the content of the target element.
  • The second declaration applies an inline-table display property, exclusively for the benefit of IE/Mac.
  • At this point, we use the comment-backslash hack to hide the remainder of the rules from IE/Mac. This enables us to do the following:
  • Apply a 1% height only to IE6 to trigger hasLayout (which is required for the hack to work)
  • Re-apply display:block to everything except IE/Mac
  • The last line is a comment that serves to close the hack for IE/Mac

As you can see, that’s a lot of fuss over a browser that has been dead for at least the last three or four years. Nobody uses IE/Mac anymore, so it is time to drop it from the clearfix hack. The result is a much cleaner and more efficient slice of CSS:

/* new clearfix */
.clearfix:after {
	visibility: hidden;
	display: block;
	font-size: 0;
	content: " ";
	clear: both;
	height: 0;
	}
* html .clearfix             { zoom: 1; } /* IE6 */
*:first-child+html .clearfix { zoom: 1; } /* IE7 */

Stripping out that IE/Mac cruft cleans things up real nice. Notice that we have further improved the clearfix hack by adding support for IE7. Neither IE6 nor IE7 support the :after pseudo-class used in the first declaration, so we need an alternate method of applying the clearfix. Fortunately, applying zoom:1 to either browser triggers IE’s proprietary hasLayout mechanism, which works just fine to clear the float. For expediency’s sake, we accomplish this with a couple of valid browser-specific selectors, but you should be advised that conditional comments are the recommended way to go.

Fortunately, IE8 supports the :after pseudo-class, so this new clearfix method will only become more simplified as IE6 and, eventually, IE7 finally die off.

Bottom line: The new clearfix method applies clearing rules to standards-compliant browsers using the :after pseudo-class. For IE6 and IE7, the new clearfix method triggers hasLayout with some proprietary CSS. Thus, the New Clearfix method effectively clears floats in all currently used browsers without using any hacks.

About the Author
Jeff Starr = Web Developer. Security Specialist. WordPress Buff.
The Tao of WordPress: Master the art of WordPress.

149 responses to “The New Clearfix Method”

  1. for me, if div float are inside a div … if the container div has :

    overflow : auto;

    it resolves ALL. On all browsers.

  2. Rod – It adds scrollbars half the time – duh

  3. Ryan Williams 2009/12/13 7:07 am

    Keeping code valid is primarily useful for troubleshooting. It may be a bad habit, but I often forget to include a semi-colon or a closing bracket, or perhaps I’ll accidentally use a colon.

    This obviously screws up the site, and so the first step is to check the validity of the CSS. If I have to navigate through CSS that contains many validation issues, it takes me considerably longer to do this.

    Obviously using one fix like the clearfix technique isn’t going to be too problematic, but if you have a front-end developer who habitually fills his CSS with ‘harmless’ invalid CSS it soon gets frustrating.

    And I stand by the assertion that there’s never a need for invalid CSS. If you want to use ‘zoom’ to throw IE into hasLayout, use one of the other valid properties that does the same thing.

    Regarding the clearing method as a whole, like I said earlier on I prefer to use ‘overflow: hidden’ (notauto’) and then give it something to throw IE into hasLayout mode such as a width. This can obviously clash with heights, but if you need to clear a parent then it’s exceedingly unlikely you’ll be using a height anyway. Works for 99% of cases in my experience.

  4. Nice way of triggering the hasLayout property in IE using the zoom: 1 property. I have to agree that while height: 1% seems to be a predominant method to trigger hasLayout, it may be problematic under certain specific consequence.

    I’m not too concerned about making my stylesheet 100% CSS 2.1 valid since we have moved on to adopting various new properties introduced in CSS3 without making a big mess with browsers that don’t support (they just degrade gracefully, something that I really love). I’m not going to crack my brain just because border-radius or text-shadow fails to validate, so I won’t be too concerned with using zoom: 1 as well.

    In the past I was using an empty <div> and making it clear both sides of the float (left and right). Later down the road I focused a little more on proper, valid semantics and so I ditched the empty <div> idea and settled for the handy clearfix method instead.

    Sometimes I’ll use the overflow: auto; method but it seems that it only works when you have a predefined width / height for the child elements. When that doesn’t work I’d rollback to clearfix :)

    What are your thoughts on overflow: auto;, Jeff?

  5. Jeff Starr 2009/12/13 2:58 pm

    Hey Teddy, thanks for the great comment. Everything you say makes good sense. As for overflow:auto, I can’t recommend it for layout elements because of the possibility of unexpected/unwanted scrollbars for overflow content. Blogs especially tend to include lots of long URLs and whatnot, and if not carefully implemented, setting the overflow to auto can be problematic (and difficult to detect without constantly visiting old posts and comments, especially when redesigning).

    I agree with everyone else that overflow:hidden works fine in most situations, but there are plenty of cases where even that is going to cause layout issues. The new design for Perishable Press is an example — I tried using overflow:hidden for the sidebar and main content area, but kept having difficulties getting other elements to behave properly. That was one of the catalysts for reworking the clearfix class — I needed to clear floats effectively in all browsers with zero side-effects. My solution has worked well so far..

  6. @Teddy,
    The difference is, border-radius and text-shadow will be W3 Recommendations in the future, while zoom won’t be.

    My current preferred method:

    /* Float clearing for IE6: */
    * html .clearfix
    {
          height: 1%;
          overflow: visible;
    }
    /* Float clearing for IE7: */
    *+html .clearfix
    {
          min-height: 1%;
    }
    /* Float clearing for everyone else: */
    .clearfix:after
    {
          clear: both;
          content: ".";
          display: block;
          height: 0;
          visibility: hidden;
    }

  7. Jeff Starr 2009/12/13 3:20 pm

    @Gary: that’s a mouthful! I guess if it works for you, then great, that’s what you should use. Personally, I always look at the work of the person who is recommending a technique before using it myself. Kind of a “show-don’t-tell” sort of thing. Thanks for chiming in! :)

  8. I’d disagree that it was a mouthful – minified, it’s only 4 characters more than your suggestion, and mine doesn’t use proprietary styles.

    As my CSS validates, then there’s no need to start adding in conditional comments into the HTML to link in ie.css if that’s important to a designer/developer – hence, overall, my solution, on it’s own, is more compact.

    I agree that maybe the height: 1% for IE6 would cause issues in some circumstances (none that I’ve come across), but the min-height:1% would struggle to be any more invasive than zoom – you’d need a very edge case.

    I’m not sure what the “work of the person” comment was in relation to, and certainly can’t see how it was useful or relevant to the discussion? I’m not a designer, and don’t claim to be. What my sites lack in the visual prettiness mindset that you’re clearly thinking in, I make up with in development aspects in code that you can’t access. Lets stick to discussing the quality of the code – not the quality of the person adding it to the discussion.

  9. Jeff Starr 2009/12/13 5:44 pm

    Lol! Relax, Gary – it’s just a silly piece of code. No need to freak out or get upset over anything. Seriously, I appreciate your comment and the time taken to craft such a thoughtful response. Your input is valued and contributes to the conversation. Please don’t feel otherwise.

  10. Gary, clean up your code and grab a tampon!

  11. Hi, This is very nice site & nice articles .

  12. Looks like the conversation overflowed (so to speak) into other venues. Here are a couple of interesting links for more information and discussion on the clearfix method:

    Andy Ford explains why he’s saying goodbye to the overflow:hidden hack.

    Snook tweets some additional downsides to the overflow:hidden hack: http://twitter.com/snookca/status/6532105759

    Snook tweets that he uses zoom for IE: http://twitter.com/snookca/status/6531243562

    Update: 2010/6/14: links to Snook’s tweets removed.. apparently he deleted those particular tweets (or something else happened).

    Update: Here is the first deleted tweet: http://dvlprs.com/snookca/statuses/6532105759 (if it mysteriously disappears, let me know, I have a screenshot this time)

Comments are closed for this post. Something to add? Let me know.
Welcome
Perishable Press is operated by Jeff Starr, a professional web developer and book author with two decades of experience. Here you will find posts about web development, WordPress, security, and more »
.htaccess made easy: Improve site performance and security.
Thoughts
I live right next door to the absolute loudest car in town. And the owner loves to drive it.
8G Firewall now out of beta testing, ready for use on production sites.
It's all about that ad revenue baby.
Note to self: encrypting 500 GB of data on my iMac takes around 8 hours.
Getting back into things after a bit of a break. Currently 7° F outside. Chillz.
2024 is going to make 2020 look like a vacation. Prepare accordingly.
First snow of the year :)
Newsletter
Get news, updates, deals & tips via email.
Email kept private. Easy unsubscribe anytime.