The New Clearfix Method

Post #728 categorized as Presentation, last updated on Jul 18, 2010
Tagged with code, css, hacks, ie, notes, tips

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 about the original 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.

Translations

Subscribe to Perishable Press


161 Responses

TopLeave a comment

[ Gravatar Icon ]

#1Adub

Besides older, non-compliant browsers, whats the point of the first block of css when you can just use clear:both;? I know that Chris Coyier uses clear:both; all of the time and seems to have little problems with it.

So, in short, my question is this: For compliant browsers, why use multiple lines of css when you can theoretically just use 1?

[ Gravatar Icon ]

#2Jeff Starr

Hi Adub, unless I’m missing something, clear:both; is useful for clearing adjacent floats, but it is insufficient to actually get container floats to clear floated child elements (such as divs).

[ Gravatar Icon ]

#3Adub

Ah, okay. It seems that the manner used by Chris is slightly different. He appears to use another child to perform the clearing inside the parent, rather then apply the class to the parent itself. Unless I’m mistaken.

[ Gravatar Icon ]

#4Ryan Williams

Both are valid ways. I tend to lean towards accomplishing the clearing without any extra HTML, therefore I use both the parent and child clearing approaches.

With that said, I’m not fond of verbose methods like Jeff’s and instead prefer to go with the overflow + dimension technique. It’s two lines, and works reliably so long as your CSS is compatible with specifying a width or height on the parent (almost always is in my experience).

[ Gravatar Icon ]

#5Jeff Starr

@Ryan Williams: yes, the overflow fix also works great in many scenarios, and is my preferred method as well, but there are situations in which it leads to further design complications. Good examples include missing vertical scrollbars on small windows, problems with borders, padding/margin issues, outline issues, and lots of other subtle nuances. Basically, any properties made possible with some sort of a visible overflow are eliminated once you change it to hidden. This can lead to all sorts of gotchas, especially in complex layouts. Other cases where the overflow method fails is when widths or heights cannot be set explicitly, which in my experience is in a fair number of situations.

Here is another situation where overflow fails.

I was going to mention this line of thinking in the article, but I knew that I would have the chance to do it in the comments ;)

[ Gravatar Icon ]

#6TeMc

That’s right Adub.

If you’re willing to add an extra [div] in your code then clear:both (either inline-styling or css-class) is all you will ever need (for ALL browsers).

However, if you rather have a div-container with in it a float-left and float-right and automaticly clear the float after the second div, then you need to “insert” an extra block-element (*:after’s are display:inline by default), that is both invisible, block-level and clearing the float.

Hm… now that I’m thinking.. I never used the word “Insert” in this context before. Makes me think…. jQuery ?

That’d work too !

$ .clear-fix.parent().append("div class clearboth");

[ Gravatar Icon ]

#7Jeff Starr

@TeMc: oooh, really like the jQuery approach :)

[ Gravatar Icon ]

#8Rob Flaherty

Instead of using the invalid zoom:1 for IE7 and IE6, why not use display:inline-block for IE7 and height:1% for IE6? Those both trigger hasLayout while still using valid CSS.

Personally I usually use the overflow method for clearing floats nowadays.

[ Gravatar Icon ]

#9Jeff Starr

@Rob Flaherty: good call, I thought about using height:1% for the new method, but it introduces potential issues with certain layouts in IE. Besides, zoom is invalid only because it is proprietary, and even then it doesn’t matter because they are only applied to the two different versions of IE. If we follow the recommended approach and use conditional comments to include the zoom declarations, then all is well and the main stylesheet will still validate.

In any case, it is up to you — you will use whichever property you wish for triggering hasLayout in IE. zoom is my choice because I find it the least invasive.

As for the overflow method, see my previous comment.

[ Gravatar Icon ]

#10Jaime

I generally use the overflow method since I’m really an advocate of not using unsemantic classes unless completely unavoidable. That said, I do use clearfix sometimes, but I either use it through mixins or I just repeat add the div’s selector to a clearfix code block. It might be a bit more work than just making a clearfix class, but the peace of mind it give me is mind boggling.

Instead of => .clearfix:after {

Id rather do tag.class1:after, tag.class2:after .... {

It keeps the layout in the CSS where it should be.

[ Gravatar Icon ]

#11Ryan

Thanks for the update. Btw, for IE 7 you can use the selector *+html for targeting. Makes it a little easier to type.

[ Gravatar Icon ]

#12Vladimir Carrer

Thanks for the update. I will make all the test later for all my CSS Frameworks.

[ Gravatar Icon ]

#13Paul Irish

Do you even need to target the zoom to only ie6/7 ?
I’d just put zoom inside the main declaration.

[ Gravatar Icon ]

#14Paul Irish

I obviously don’t read before I post.. sorry.

I’d just do a

.clearfix { *zoom: 1 }

But that’s me and my quick unvalidating hacks.

[ Gravatar Icon ]

#15kcmr

I use min-height: 0 for IE 7 instead zoom: 1, and height: 1% for IE 6
This is valid CSS and has no effects for other browsers.

.clearfix{min-height: 0;} /* IE 7 */
* html .clearfix{height: 1%;} /* IE 6 */

I also aply this rules to all divs to avoid use continuosly the clearfix class in the HTML code.

div:after{... }
div{min-height:0;}
* html div{height: 1%;}

[ Gravatar Icon ]

#16Victor Teixeira

hmmm… The clearfix that I use is like this:

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

And the IE6 part:

* html .clearfix {height: 1%;}

[ Gravatar Icon ]

#17Jorik

What about this? works in all browsers i believe…

.clearfix { overflow: hidden; }
/* ie part */
.clearfix { zoom: 1; }

[ Gravatar Icon ]

#18Jeff Starr

@Jaime: mind-boggling, eh? sounds like a lot of work to me..

@Ryan: thanks for the targeting tip! :)

@Vladimir Carrer: cool, thanks for the feedback.

@Paul Irish: hey if it works, it works - validation is merely a tool, right?

@kcmr: I like the idea of using min-height:0 for IE7, but not height:1% for any browser because, even though it’s valid, it can produce unintended side-effects in certain layouts. Also, applying the clearfix to all divs may be overkill.

@Victor Teixeira: see this comment.

@Jorik: see this comment.

To all: Thank you everyone for the great feedback on this topic. Good to see everyone doing their own thinking instead of just taking my word for it. Cheers! :)

[ Gravatar Icon ]

#19Jorik

@jeff
True, that is sometimes a big problem..!

[ Gravatar Icon ]

#20Justin

Hey Jeff, discovered your blog after picking up your new book with Chris Coyier, great stuff.

Question about the clearfix - it looks like you’re applying it directly to specific elements in your css as opposed to adding the class in the markup. Do you reccommend doing this instead?

[ Gravatar Icon ]

#21Jeff Starr

Hi Justin, good question - I think the code uses a .clearfix class that could be applied to any element in the markup, but you could also apply the fix directly to any existing element according to its class, id, or name. Either method works fine in my experience. Using a .clearfix class is useful when there are multiple elements that need the fix, but if it’s just a single instance, I would apply the fix directly.

Btw, nice to meet you, and thank you for picking up a copy of Digging into WordPress :)

[ Gravatar Icon ]

#22Pete

This is a great method that I’ve been using for a while with no problems: http://www.quirksmode.org/css/clearing.html

[ Gravatar Icon ]

#23Justin

Thanks Jeff, i’m just getting into WordPress, and I’ve picked up a lot from the book already, it’s been very helpful!

I’ve been using a blank div with a clear="both" until now, but think I’ll give this a try on my next project.

[ Gravatar Icon ]

#24Jeff Starr

@Pete: yes, we have been over that several times now. See this comment for more information.

@Justin: awesome, great to hear it (on both points)! =)

[ Gravatar Icon ]

#25iPad

Jeff I think you should call it “A cleaner clearfix” instead of “The new clearfix” ;) my 2¢

[ Gravatar Icon ]

#26Jeff Starr

iPad, that sounds good too, but I want to emphasize that the old way of doing it is no longer necessary, and that we have a new and improved method. Although I’ll admit that “cleaner clearfix” does sound nice ;)

[ Gravatar Icon ]

#27a guy

Seems too complicated… I used to use the overflow method, but I just float the parent div, then it wraps all child floats…

so:

div “content” is floated left inside the “wrapper” div. Content div will wrap around the two “left and right” floated divs… so you can add a border etc etc… simple. Works everything for me…

[ Gravatar Icon ]

#28Jeff Starr

@a guy: yes, the FNE (Float Nearly Everything) method is another viable method for clearing floats, but unfortunately there are many situations where floating everything is not an option. It all depends on the needs of the design, so it’s good to have a variety of options available.

[ Gravatar Icon ]

#29iVane Hwang

I alway do like this:

.clearfix {zoom:1;}
.clearfix:after {content:""; clear:both; display:block; height:0;}

[ Gravatar Icon ]

#30Justin

Someone can correct me if I’m wrong, but I think you avoid that because the zoom:1 property doesn’t validate and needs to be fed only to IE on conditional stylesheets.

[ Gravatar Icon ]

#31Jeffrey

I use

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

html>body .clearfix { display: block; }
.clearfix { display: inline-block; }
* html .clearfix { height: 1%; }

Valid CSS (“zoom” isn’t).

[ Gravatar Icon ]

#32Nikola

My version:

/* Clear Fix */
.fix:after {
      content: '[.]';
      display: block;
      height: 0;
      clear: both;
      visibility: hidden;
}
.fix {
      display: inline-block;
}
/*\*/
.fix {
      display: block;
}

[ Gravatar Icon ]

#33DRoss

All the retards trying to explain how the clear differently - youre retards who arent good front-end developers. Use clearfix, thank me later - you should have known about this for 3 years.

[ Gravatar Icon ]

#34Jay

Is this really a new method, or have you just taken what people have been doing for years and removed all references to IE5?

I’m not seeing anything “new” here.

[ Gravatar Icon ]

#35Victor Nogueira

I don’t know why people care so much about validating their code. To me it’s like an obsessive–compulsive disorder.

Don’t get me wrong, I always validate my HTML/CSS, but I just ignore obviously invalid properties such as “-moz-border-radius” or “zoom”. zoom: 1 is just fine. It doesn’t screw anything, it stays quiet and safe.

I understand coders who avoid non-semantic classes, though. I’m part of this group, but I make some exceptions, as I always use classes like “hidden” (for image replacements) and “clearfix”, as it saves me a lot of time.

Anyway, thank you for the update. I’m already using it.

[ Gravatar Icon ]

#36Marco

Caring if your css validates is old school and pointless.

[ Gravatar Icon ]

#37Rod

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

overflow : auto;

it resolves ALL. On all browsers.

[ Gravatar Icon ]

#38Marco

Rod - It adds scrollbars half the time - duh

[ Gravatar Icon ]

#39Ryan Williams

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.

[ Gravatar Icon ]

#40Teddy

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?

[ Gravatar Icon ]

#41Jeff Starr

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..

[ Gravatar Icon ]

#42Gary

@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;
}

[ Gravatar Icon ]

#43Jeff Starr

@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! :)

[ Gravatar Icon ]

#44Gary

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.

[ Gravatar Icon ]

#45Jeff Starr

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.

[ Gravatar Icon ]

#46Marco

Gary, clean up your code and grab a tampon!

[ Gravatar Icon ]

#47james

Hi, This is very nice site & nice articles .

[ Gravatar Icon ]

#48Jeff Starr

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.

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)

[ Gravatar Icon ]

#49Sal B

I’ve used overflow:hidden; on the containing element and that usually works out fine.

[ Gravatar Icon ]

#50Jeff Starr

Hi Sal, that method definitely works in some situations, but there are good reasons why it isn’t a one-size-fit-all solution for clearing floats.

[ Gravatar Icon ]

#51Teddy

@Gary: Oooh boy. Here’s a chill pill for you :) anyway, yeap I agree that zoom: 1 is a proprietary property meant for IE but what I personally feel is that it doesn’t hurt to include it even if it invalidates your CSS. I used to be a validation OCD back then but now I’ve learned to let things go, teehee.

@Jeff: Oh yea, the overflow: auto property may give rise to some problems if the content overflows. My bad! I wasn’t thinking straight when I typed that out and I recommend overflow: hidden instead, heh. And speaking of layout problems, overflow do give certain layout inconsistencies across some browsers under certain circumstances (I sound very general here because I forgot how to trigger the problems - I swear I found a ton of them when using the overflow property instead of the height fix). I guess height: 1% is still the way to go. Have a great week ahead yea!

[ Gravatar Icon ]

#52Florian Purchess

Hey Jeff, I always use http://www.webtoolkit.info/css-clearfix.html in my projects and it’s basic part of my css-lib. In ref of your title: How much do you consider it as new? Why do you prefer inline-table instead of inline-block, which is more common? Greetz, Flo :)

[ Gravatar Icon ]

#53Jeff Starr

Hi Florian, good questions - if you read through the article, you will see that I mention my previous work on the clearfix hack, which implements some new properties and modifies some existing ones. These improvements are now used together with the further changes made in this article, which consist mostly of eliminating IE5 support, simplifying for IE6, and including explicit mention of IE7.

As for why I prefer “inline-table” instead of “inline-block,” well actually if you look closely you will see that neither of these property values are used in the “new” clearfix class.

[ Gravatar Icon ]

#54Ingo Chao

small notes:

- IE7 was already supported. http://ago.tanfa.co.uk/archives/300.html

- Your maintenance work on the old Aslett/PIE hack should at least link to the original method and their authors. /They/ did something “new”.

- “without using hacks” … adding a pseudo-element to a container to let it contain its floats is of course hack. Not to speak from that zoom you are sending to IE.

[ Gravatar Icon ]

#55Jeff Starr

@Ingo Chao: some good points, especially on the IE7 support — I rescind my previous comment concerning it. For your second point, re-check my work on the original method: the fifth word into the post — and the very first link — credits the original PIE method. Beyond that, I’m going to have to disagree that using valid CSS such as the :after pseudo-element to achieve design goals is in any way a “hack.” There are no “rules” as to how valid CSS may be used in web design. And, just because zoom is proprietary doesn’t qualify it as a hack either. I clearly state in the article that the IE rules should be delivered directly via conditional comments.

[ Gravatar Icon ]

#56Jens Grochtdreis

The idea to drop IE5Mac is okay. You could reduce the last two rules to only one rule. The zoom-property is only understood by IE. And a star in front of a property is only read by IE6 and 7. So why not write:

.clearfix { *zoom: 1;}

BTW: it is possible, that IE8 doesn’t understand “zoom”. Given that we could drop the star, too.

[ Gravatar Icon ]

#57Jeff Starr

@Jens Grochtdreis: good call - I was just thinking something similar about consolidating the zoom property into the .clearfix:after selector. Much cleaner, but still best to deliver it via conditional comments I think. Thanks for the comment :)

[ Gravatar Icon ]

#58Jens Grochtdreis

@Jeff: You cannot consolidate the zoom-property into .clearfix:after, because IE6 (and 7?) won’t see it. ;-)

Of course the best way would be to split the rules into a normal stylesheet and an IE-CSS. But sometimes it is best to keep them together os you can easily teach the rules and transport them to another project.

[ Gravatar Icon ]

#59Jeff Starr

@Jens: Doh! That’s very true - and a sign that I have spent too much time at the computer today ;)

[ Gravatar Icon ]

#60Ionut Botizan

.clearfix {
          min-height:0;
          height:auto !important;
          height:0;
          }

One definition for both IE6 and IE7, with valid CSS rules and min-height hack:

min-height:0; will trigger hasLayout in IE7

height:auto !important; will preserve auto height for all browsers, except IE6

height:0; will trigger hasLayout in IE6, but won’t affect other browsers, because of the previous rule (which IE6 ignores in this situation)

[ Gravatar Icon ]

#61Jeff Starr

@Ionut Botizan: interesting approach. It looks a lot like Dustin Diaz’ minimum-height fix for IE:

selector {
       min-height: 500px;
       height: auto !important;
       height: 500px;
       }

Do you think there might be any side-effects in certain conditions when setting the height to zero in IE and ‘auto’ in other browsers?

[ Gravatar Icon ]

#62Ionut Botizan

P.S.: Check your Gravatar settings. My avatar has a PG (Parental guidance recommended) rating. You should use G (General Audience) if you would like to avoid that kind of profanity appearing on your blog.

[ Gravatar Icon ]

#63Jeff Starr

Thanks for the tip, Ionut, but I thought it was cute and don’t really have a problem with it ;)

[ Gravatar Icon ]

#64Ionut Botizan

The 2 things I can think about are:

1) The container for the floated elements has overflow set to hidden or auto.
In this case, IE6 will apply the overflow and height rules, so it won’t stretch the container to match its contents. However, if you have overflow set to one of those, then you won’t need to apply the clearfix class, since overflow set to hidden or auto will clear the floats.
So, everything should be ok in this case.

2) The container has a fixed height.
If that’s the case, you might need to use !important in the rule where the container’s height is defined. However, I’m not completely sure that this will be necessary, since floats inside a fixed height container shouldn’t cause any problems. So, once again, you can get away with it by simply not using the clearfix class at all.

…And you were right! That solution is based on the min-height fix for IE6, but I’m not good at names, so I didn’t remembered who came up with that! :D

[ Gravatar Icon ]

#65Jeff Starr

@Ionut, thanks for the followup. Definitely seems like that method could be useful for clearing floats (and fixing min-height!). I haven’t tried it yet, but will certainly give it a try for my next design. Do you have any live examples where this technique is being used?

[ Gravatar Icon ]

#66Patrick

This is almost exactly what I’ve been doing for the last 2 years. Except I’ve been using: .clearfix {*zoom:1;} and have yet to run into issues with it.

I don’t like the old method of using height to trigger hasLayout because it’s a valid property and I prefer to use valid properties for valid purposes. The proprietary zoom property is perfect for this: I’d never use it anywhere else, so I’ll never run into any cascading or inheritance issues.

[ Gravatar Icon ]

#67Chris Coyier

This is definitely the way to go for clearing floats. As someone mentioned above, yes, sometimes I opt for a clearing div, but only in circumstances where you’d need to add more wrapping divs than you would clearing divs. For example:

[ ] [ ] [ ]
-- clearing div / --
[ ] [ ] [ ]

is easier then

-- wrapping div --
[ ] [ ] [ ]
-- / wrapping div --

-- wrapping div --
[ ] [ ] [ ]
-- / wrapping div --

But that’s not my main point here. I wanted to say that Dan Cederholm has been spreading a clever alteration to this and that is to call the class name “group” or “container” rather than “clearfix”. I know it kinda feels like an irrelevant wording change, but that’s what semantics basically is. To me, it just FEELS better wrapping stuff in a div called “group”. It feels like you are doing it for organization rather than a “fix”.

[ Gravatar Icon ]

#68gaowhen

As I know, IE6/7 can be targeted by *. So, maybe this method can be written like this :

.clearfix:after {
       visibility: hidden;
       display: block;
       font-size: 0;
       content: " ";
       clear: both;
       height: 0;
       zoom:1;
}

I wonder why you choose such a complex method to target IE6/7.

[ Gravatar Icon ]

#69Jeff Starr

@Chris: absolutely, avoiding the word “fix” in your code is probably a good thing, but I would rather just use the class (or ID) name of the target element rather than “group.” If you think about it, <div>s generally “group” or “contain” their contents, so applying a selector with either of these names is probably a bit redundant and not necessarily more semantically precise than “clearfix.” I think maybe just simplifying the name to “clear” would be more beneficial maintenance-wise. But either way, whatever works best for the individual designer is the way to go.

@gaowhen: good idea, but unfortunately IE6/7 doesn’t understand the :after pseudo-element.

[ Gravatar Icon ]

#70gaowhen

sorry I made a mistake. I should use zoom:1 to trigger the haslayout of .clearfix, not the .clearfix:after. So it should be like this:

.clearfix:after {
       visibility: hidden;
       display: block;
       font-size: 0;
       content: " ";
       clear: both;
       height: 0;
}
.clearfix{*zoom:1;}

How about this one?

[ Gravatar Icon ]

#71Jeff Starr

@gaowhen: um, I think Patrick already mentioned this a few comments up. But either way, it doesn’t matter because the code is invalid.

Try again?

[ Gravatar Icon ]

#72Martin

In most cases .clearfix { overflow: hidden; zoom: 1; } is all I need. The zoom is moved to a dedicated CSS file for those obsessed with validation.

[ Gravatar Icon ]

#73Jeff Starr

@Martin: interesting because most of the time floats also need to be cleared in non-IE browsers, which is something that zoom:1 can’t really do.

[ Gravatar Icon ]

#74Martin

Of course Jeff, you know it’s know the zoom property which is doing the “clearing”.

I simply prefer this solution to yours because it’s less obtrusive (although the obtrusion is not visible and works just as fine).

It all boils down to the personal preferences and the layout-in-development.

[ Gravatar Icon ]

#75Jeff Starr

I thought zoom was proprietary exclusive to Microsoft, meaning that it is insufficient to clear floats in anything other than IE. So yes, it does the clearing, but only for IE, correct? To clear floats in all non-IE browsers, additional code is needed (e.g., the :after rules in the clearfix method. Or maybe I have been slurping too much cough medicine..?

[ Gravatar Icon ]

#76Martin

Uhh, I only hope we understand each other correctly ;)

Back in the days I used to manually insert a clearing span after the floats I wanted to clear, which was my bulletproof and cross-browser implementation of the :after trick.

But lately I am very much into overflow: hidden;, which is much simpler, and allows a container to have as many floats inside it and still not loose its height, meaning that it acts as a float clearer. So all we just add the zoom for the IE.

I am sure you know everything I’m talking about here, but for illustration purposes, here are some live examples I just sketched up: http://martin.saulis.com/test/floats.html

So, I am not arguing the different tricks to achieve a desired result — I am solely expressing my opinion on the advantages of using a simpler approach ;)

[ Gravatar Icon ]

#77Jeff Starr

@Martin: lol! Okay so now you’re talking about the overflow:hidden method? What about your “all I need” zoom-only method..? I’m feeling cheated here.

In any case, I think we have pretty much hammered the whole overflow:hidden thing to death in this comment thread, so no need to waste any more time regurgitating stuff.

[ Gravatar Icon ]

#78Jaime

@Jeff: “In most cases .clearfix { overflow: hidden; zoom: 1; }” I think he made it pretty clear he was talking about using the overflow: hidden method, while using zoom for ie only.

[ Gravatar Icon ]

#79Jeff Starr

whoa! yes, you are correct - I totally did not see that overflow:hidden was included in there. Apologies to Martin - everything makes sense now. You are correct on all points - apparently my cold medicine is a little too strong.

Now please kick me in the lower jaw for good measure ;)

[ Gravatar Icon ]

#80Jaime

Lol no kicking needed I believe. For what it’s worth I rather just add clearing rules to individual selectors via mixins with whatever your preference in css frameworks is. keeps everything 101% semantic and is easier to maintain than using a clearfix class.

[ Gravatar Icon ]

#81Eric Hobart

Can I get some opinions re this clear technique…I’m using it with success:

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

thanks for you input,
Eric

[ Gravatar Icon ]

#82Jens Grochtdreis

@Eric: Please try next time to read the article first and then post a comment. If you had read the article you would have recognized, that you posted a part of the original clearfix-hack which the article discussed top modernise. Reading and thinking doesn’t hurt, you know?

[ Gravatar Icon ]

#83Jeff Starr

Eric, yeah that is a part of the original (old) clearfix article on which this method improves imho.

[ Gravatar Icon ]

#84tanya singh

I don’t use clear fix, learned to avoid that piece

[ Gravatar Icon ]

#85Martin

@tanya singh:

I find it hard to believe that, unless you’re not using floats — and they’re the most commonly used layout modifying properties!

[ Gravatar Icon ]

#86paul

hmm, I’m using the clearfix on a continre div ith 4 floated div inside and in IE7 it didnt hae ny effect
I had to use overflow:hiddennn

[ Gravatar Icon ]

#87Know

I don’t use clear fix too!

[ Gravatar Icon ]

#88Monsoon

Thanks a lot for this article, really helped me out today! Tried a couple of other clearfix-solutions, but this was the best one, cheers.

[ Gravatar Icon ]

#89Andiv Sites

Sometimes a lot better to leave as is Tk. Thank you! Great post!

[ Gravatar Icon ]

#90Clares

I was going to mention this line of thinking in the article, but I knew that I would have the chance to do it in the comments

[ Gravatar Icon ]

#91JohnONolan

This line does NOT work, it triggers a bug in Firefox 3

content: " ";

This needs to remain (as in the old version) as content: ".";

[ Gravatar Icon ]

#92Jeff Starr

@JohnONolan: Thanks, but I have not experienced anything weird in Firefox. What seems to be the exact issue?

[ Gravatar Icon ]

#93avajayam

It’s a complex way to fix float bug. Actually browser will work smoothly when use overflow in simple html or use additional div with clearence in complex html. Becare, the additional Clearfix class will burden the browser, like up two way. So hard to get a perfect way to fix bug when browsers are ugly.

[ Gravatar Icon ]

#94Sake

I used overflow:hidden (and auto) for a couple of projects and had some unpleasant surprises later when the client printed some of their content-heavy pages. If the content div is long and the printed content would go over one page, only the first page of content would be printed and all the remaining pages would be empty. So, back to clearfix.

[ Gravatar Icon ]

#95Luc

@Jeff Starr - I had exactly the same issue as @johnonolan - the empty content:" "; rule gave a load of weird layout issues in FF3.6 - adding the period back in fixed it all…

[ Gravatar Icon ]

#96Jeff Starr

@Luc: What was the issue exactly? I would love to check it out, but haven’t been able to recreate any issues in Fx3.6 (or otherwise). Thanks!

[ Gravatar Icon ]

#97JohnONolan

@Jeff it basically totally stops the clearfix from working and stuff goes floating all over the place - I’m on Mac FF if that makes any difference (it shouldn’t though)

[ Gravatar Icon ]

#98Andee Know

For a long time searched for something similar. Thanks!

[ Gravatar Icon ]

#99cyrylski

that was very helpful, indeed. thanks a lot!

I tried overflow:hidden but it still screwed up my layout. It’s fine and dandy now :)

My question is if this is really a fix (meaning a remedy to the cause of a problem), or rather a fix (meaning work-around to cover up a pile of mess)? :D

[ Gravatar Icon ]

#100serzhiio

Thank you, clearfix solved my problem!

[ Gravatar Icon ]

#101Jeff Starr

@JohnONolan: Thanks, I’ll run some tests and check it out. In the meantime, I would like to note that I am using this clearfix method here on this site and it works as stated in latest Firefox (currently 3.5.9).

[ Gravatar Icon ]

#102Andiv

The strength of this method - its simplicity. After all, as they say - all brilliant - just.

[ Gravatar Icon ]

#103GreLI

Why so difficult? It can be done much easier:

/* new clearfix */
.clearfix:after {
     clear: both;
     display: block;
     height: 0;
     content: "";
     }
*html .clearfix { zoom: 1 } /* IE6 */
*+html .clearfix { zoom: 1 } /* IE7 */

[ Gravatar Icon ]

#104Jeff Starr

GreLI, here is some of my reasoning for the additional rules.

[ Gravatar Icon ]

#105Thierry Koblentz

fwiw, my advice is to avoid using “clearfix”, because it has the potential to create more issues than it can solve.

http://carsonified.com/blog/design/everything-you-know-about-clearfix-is-wrong/

[ Gravatar Icon ]

#106Jeff Starr

Thanks Thierry! Looks like some great advice :)

[ Gravatar Icon ]

#107Martin Chaov

Or you can just use overflow: hidden; on the container as listed in specs (http://www.w3.org/TR/CSS2/visuren.html), and never again use hack to fix issues that do not exist…

[ Gravatar Icon ]

#108Jeff Starr

The issues definitely exist, unfortunately. As discussed quite thoroughly in this thread, different methods have different shortcomings, but it is nice to have a variety of solutions available for those tricky cases.

[ Gravatar Icon ]

#109Martin Chaov

@Jeff Starr,

There are several known case when one could or need to use another method of clearing floats, but as I’ve said before - overflow:hidden; fixes most common cases and by specification must be used on containers with floated children.
Have I mentioned that as this is from the box model specs it is supported even by our beloved IE6 (also lesser versions but they do not concern us).

There isn’t need for different methods and their shortcomings :).

two simple ways of clearing floats - clear: both assigned to the element that goes after your floated queue, if the case is special and overflow: hidden; on the container when the case is general.

[ Gravatar Icon ]

#110Ali

I’d go with overflow + dimension.

[ Gravatar Icon ]

#111Jeff Starr

Again, the overflow method definitely works in some situations, but there are good reasons why it isn’t a one-size-fits-all solution for clearing floats. Read through the thread for the full discussion, or check out these links for more information:

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

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

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

Here is another situation where overflow fails.

Yes, the overflow fix also works great in many scenarios, and is my preferred method as well, but there are situations in which it leads to further design complications. Good examples include missing vertical scrollbars on small windows, problems with borders, padding/margin issues, outline issues, and lots of other subtle nuances. Basically, any properties made possible with some sort of a visible overflow are eliminated once you change it to hidden. This can lead to all sorts of gotchas, especially in complex layouts. Other cases where the overflow method fails is when widths or heights cannot be set explicitly, which in my experience is in a fair number of situations.

Update: It looks like Mr. Snook deleted those tweets, but he did say it.

Update: Here is proof: http://dvlprs.com/snookca/statuses/6532105759

Update again: It looks like the missing tweets happened because of a Twitter issue. My apologies to Mr. Snook for implying otherwise.

[ Gravatar Icon ]

#112Marc Watts

The best way to use a clearfix can be found at best clearfix ever. It doesn’t use class names to fix the problem but an automatic solution that should be applied to all block level elements except for the p and footer elements.

[ Gravatar Icon ]

#113Thierry Koblentz

@Marc

Best clearfix ever? You must not be serious.
Do you understand that your rules will create very different constructs across browsers?

For example, you give a layout to DIVs (div {zoom:1;}) but these do not create block formatting contexts in modern browsers.

Try to nest a bunch of DIVs and apply vertical margins to them, you’ll see that in IE 6 and 7 these margins will *not* collapse.

Check everything you know about clearfix is wrong to understand why your rules will break many layouts.

[ Gravatar Icon ]

#114August

Are comments working again?

[ Gravatar Icon ]

#115Jeff Starr

Marc Watts, there is no way that is better. Just looking at it scares the shit out of me.

[ Gravatar Icon ]

#116Thierry Koblentz

@Jeff

Regarding Jonathan Snook’s tweet. I believe this is not really related to the issue since “overflow:hidden” is not a technique, but a trigger.
The technique itself has to do with block formatting contexts, so authors can implement the method using other triggers.

In short, it is not clearfix vs. overflow:hidden it is clearfix vs. block formatting contexts

Also, if overflow:hidden affects printing then authors can easily reset this styling in their print styles sheet.

Lastly, overflow:hidden does not always cut-off content outside the element’s boundaries. It really depends on constructs.

[ Gravatar Icon ]

#117Jeff Starr

Thierry, you say:

overflow:hidden does not always cut-off content outside the element’s boundaries. It really depends on constructs.

Completely agree. I think the best thing to keep in mind is that different layouts require different solutions. There is no need to think in terms of “this vs. that” – it’s simply a matter of understanding the pros and cons of any clearing method and then using the best tool for the job.

[ Gravatar Icon ]

#118Thierry Koblentz

@Jeff

I agree, there is nothing authors should disregard. It’s a jungle out there and we need all the tools we can put our hands on.

I use the clearfix method myself, but in very rare occasions.
My addition to this technique is the use of padding declarations (padding-top:1px;padding-bottom:1px;). This is to make sure the vertical margin of the first and last child of the block will not collapse in modern browsers. I added this to the original rule because zoom:1 prevents margin collapsing. That way things look the same in all browsers.

[ Gravatar Icon ]

#119Marc Watts

@Thierry Koblentz

Thanks for your reply. I have seen your article on carsonified.

I just briefly checked it out again so correct me if I am wrong but you have 3 div elements with the two sides ones floated and the one in the middle is not floated.

To fix the problem that you have shown, you just need to float the middle div. Unless your using liquid layouts (which I don’t see anyone using anymore), then I see no reason why you wouldn’t float the middle div.

If you do then my technique still works. I suppose this means that I create websites in such a way that it works with my clearfix solution.

[ Gravatar Icon ]

#120Thierry Koblentz

@Marc Watts

If I pointed you to the article it was not in relation to a particular layout, but to what this method does to blocks.

You are giving a layout to all these elements:
article, aside, div, form, header, nav, section, and ul

This is what this means for IE 6 and 7:

1. these blocks will contain floats,
2. the border box of these blocks will not overlap floats,
3. the vertical margin of the first and last child of these blocks will not collapse.

In modern browsers, your styling will only trigger #1.

But #2 is the killer here, because - in these blocks - clearing a nested element will clear outside of the block in modern browsers, but not in IE.
For the same reason, the border box of these blocks will be different across browsers.

If you do then my technique still works. I suppose this means that I create websites in such a way that it works with my clearfix solution.

If your technique works (which I doubt) the way you create web sites, then it may be the best method for you, but it’s certainly not “the best clearfix ever” (as you claim).

[ Gravatar Icon ]

#121Marc Watts

@Thierry Koblentz

Thanks for your reply again.

Would you have an example website that you think would break my clearfix? I’ll need to do some tests to check what you are saying. So far I have had no problems using the fix.

I may have to look into this further.

Marc

[ Gravatar Icon ]

#122avajayam

Hi,someone find a bug in ie7(I think it is not about float, but hope the new clear can fix it, because additional clear div can fix it), cann’t give the margin-bottom 10px yet. The code as follow:

Try

.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 */

[ Gravatar Icon ]

#123avajayam

sorry the > < be clear

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Try</title>
<style type="text/css">
.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 */
</style>
</head>
<body>

<div style="width:600px;border:1px solid #69C;" class="clearfix">
       <div style="width:480px;height:24px;background-color:#69C; margin:10px; float:left;"> </div>
</div>

</body>
</html>

[ Gravatar Icon ]

#124Marc Watts

If you’re having problems with vertical margins then I would recommend using padding instead. It eliminates any collapsing problems.

[ Gravatar Icon ]

#125Thierry Koblentz

@avajayam

This is a IE6/7 bug. afaik, to create space below the float you’d need to use padding on the wrapper rather than margin on the float.
Note that this has nothing to do with margin collapsing.

[ Gravatar Icon ]

#126avajayam

Thanks Marc and Thierry(Great).

[ Gravatar Icon ]

#127Website design chennai

Thanks to Jeff Starr sharing about new The New Clearfix Method..Fine

[ Gravatar Icon ]

#128Dawn

I’m sorry to ask such a newbie question but my head is swimming. How does this work out in the HTML?

This works for me in Firefox but I don’t know if this works in IE.

<a href="index.html" rel="nofollow">Home</a>
<a href="../store/index.html" rel="nofollow">Store</a>

<!-- end of navigation div -->

or should I say

Thank you.

[ Gravatar Icon ]

#129Dawn

Sorry. Code didn’t work after I hit submit button, I’ll try again.

In HTML would I use:

<div id="navigation.clearfix">
     <ul id="navigation">
     </ul>
</div>

or

<div id="navigation.clearfix:after">

Lastly, how are people able to type the lesser than and greater than symbols?

Thank you.

[ Gravatar Icon ]

#130Jeff Starr

Hi Dawn,

I tried rescuing your code, but it looks like WordPress pretty much mangled it. The easiest way to ensure your code stays intact is to wrap each line (or term) with <code> tags. Something like this:

<code><div></code>
       <code><p></code>
       <code></p></code>
<code></div></code>

I hope that helps. Feel free to repost your code using that method. The less-than and greater-than symbols should display just fine with the code tags.

Trackbacks / Pingbacks

  1. Twitter Trackbacks for The New Clearfix Method • Perishable Press [perishablepress.com] on Topsy.com
  2. tripwire magazine | tripwire magazine
  3. uberVU - social comments
  4. The New Clearfix Method
  5. The New Clearfix Method • Perishable Press « Netcrema – creme de la social news via digg + delicious + stumpleupon + reddit
  6. === popurls.com === popular today
  7. Descubrimientos del 7 Diciembre 2009 | Blog de unique3w
  8. links for 2009-12-07 « Mandarine
  9. A New Clearfix Method | Synergystars
  10. Heti események | I build websites
  11. links for 2009-12-08 | Starving Designer :: Be Awesome!
  12. 80+ Stunning Community Links for Web Designers and Developers | tripwire magazine
  13. 80+ Stunning Community Links for Web Designers and Developers | Afif Fattouh - Web Specialist
  14. Clearfix Hack « Randomos Technos
  15. CSS: El nuevo método Clearfix para quitar floats - elWebmaster.com
  16. links for 2009-12-10 « toonz
  17. BlogBuzz December 12, 2009
  18. Daily Digest for December 12th | More Than Scratch The Surface
  19. “Sunday Special” Round-Up II | The Phuse
  20. links for 2009-12-13 « BarelyBlogging
  21. スタイルシートの基礎編からCSS3応用編まで | Nutspress
  22. Twitter « Yolanda
  23. Novo método para aplicar ClearFix | Wildiney Di Masi
  24. 清除浮动新说 – SHOPEX模板,ECSHOP模板,ZEN CART模板
  25. 清除浮动新说 | CSS | 前端观察
  26. The New Clearfix Method — MooTools and CSS Resources
  27. How to Build a jQuery Brush Stroke Navigation | Onextrapixel - Showcasing Web Treats Without Hitch
  28. (New) Clearfixハック | CSS Radar
  29. How to Build a jQuery Brush Stroke Navigation | eGuids.Com
  30. BLARGH!! for the people » Seven CSS Tricks No One Should Ever Have to Memorize
  31. 50 New Useful CSS Techniques, Tools and Tutorials - Smashing Magazine

Share your thoughts..

TopRead official comment policy

The rules are simple. Comment intelligently. Stay on-topic. Don’t spam! Suspected spam will be deleted. Use your real name or nickname, not a site name or business name. Using a site name or business name is a good way to get your link or comment removed. Certain comments are moderated; if your comment does not appear after several days, or if you wish to comment privately, contact me. Also, by posting a comment, you grant this site a perpetual license to reproduce your comment, name, and website URL. Lastly, you may use basic HTML markup, but please do not use <pre> tags. Instead, wrap your code with <code> tags. Use a new set of <code> tags for each code term or phrase, as well as for each individual line of code (i.e., multiple lines of code require multiple code tags). Please see the complete comment policy for more information.