The New Clearfix Method

by Jeff Starr on Sunday, December 6, 2009 118 Responses

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.


118 Responses

Add a comment

[ Gravatar Icon ]

Adub#1

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 ]

Jeff Starr#2

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 ]

Adub#3

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 ]

Ryan Williams#4

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 ]

Jeff Starr#5

@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 ]

TeMc#6

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 ]

Jeff Starr#7

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

[ Gravatar Icon ]

Rob Flaherty#8

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 ]

Jeff Starr#9

@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 ]

Jaime#10

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 ]

Ryan#11

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 ]

Vladimir Carrer#12

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

[ Gravatar Icon ]

Paul Irish#13

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

[ Gravatar Icon ]

Paul Irish#14

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 ]

kcmr#15

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 ]

Victor Teixeira#16

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 ]

Jorik#17

What about this? works in all browsers i believe…

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

[ Gravatar Icon ]

Jeff Starr#18

@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 ]

Jorik#19

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

[ Gravatar Icon ]

Justin#20

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 ]

Jeff Starr#21

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 ]

Pete#22

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 ]

Justin#23

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 ]

Jeff Starr#24

@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 ]

iPad#25

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

[ Gravatar Icon ]

Jeff Starr#26

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 ]

a guy#27

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 ]

Jeff Starr#28

@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 ]

iVane Hwang#29

I alway do like this:

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

[ Gravatar Icon ]

Justin#30

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 ]

Jeffrey#31

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 ]

Nikola#32

My version:

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

[ Gravatar Icon ]

DRoss#33

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 ]

Jay#34

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 ]

Victor Nogueira#35

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 ]

Marco#36

Caring if your css validates is old school and pointless.

[ Gravatar Icon ]

Rod#37

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

overflow : auto;

it resolves ALL. On all browsers.

[ Gravatar Icon ]

Marco#38

Rod - It adds scrollbars half the time - duh

[ Gravatar Icon ]

Ryan Williams#39

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 ]

Teddy#40

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 ]

Jeff Starr#41

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 ]

Gary#42

@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 ]

Jeff Starr#43

@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 ]

Gary#44

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 ]

Jeff Starr#45

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 ]

Marco#46

Gary, clean up your code and grab a tampon!

[ Gravatar Icon ]

james#47

Hi, This is very nice site & nice articles .

[ Gravatar Icon ]

Jeff Starr#48

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.

Snook tweets that he uses zoom for IE.

[ Gravatar Icon ]

Sal B#49

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

[ Gravatar Icon ]

Jeff Starr#50

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 ]

Teddy#51

@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 ]

Florian Purchess#52

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 ]

Jeff Starr#53

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 ]

Ingo Chao#54

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 ]

Jeff Starr#55

@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 ]

Jens Grochtdreis#56

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 ]

Jeff Starr#57

@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 ]

Jens Grochtdreis#58

@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 ]

Jeff Starr#59

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

[ Gravatar Icon ]

Ionut Botizan#60

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

Jeff Starr#61

@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 ]

Ionut Botizan#62

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 ]

Jeff Starr#63

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

[ Gravatar Icon ]

Ionut Botizan#64

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 ]

Jeff Starr#65

@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 ]

Patrick#66

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 ]

Chris Coyier#67

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 ]

gaowhen#68

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 ]

Jeff Starr#69

@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 ]

gaowhen#70

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 ]

Jeff Starr#71

@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 ]

Martin#72

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 ]

Jeff Starr#73

@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 ]

Martin#74

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 ]

Jeff Starr#75

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 ]

Martin#76

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 ]

Jeff Starr#77

@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 ]

Jaime#78

@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 ]

Jeff Starr#79

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 ]

Jaime#80

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 ]

Eric Hobart#81

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 ]

Jens Grochtdreis#82

@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 ]

Jeff Starr#83

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

[ Gravatar Icon ]

tanya singh#84

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

[ Gravatar Icon ]

Martin#85

@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 ]

paul#86

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 ]

Know#87

I don’t use clear fix too!

[ Gravatar Icon ]

Monsoon#88

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 ]

Andiv Sites#89

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

[ Gravatar Icon ]

Clares#90

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

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
Share your thoughts..

Read Comment Policy

Comment Rules: No spam. No profanity. Use your real name. You may use simple HTML tags for style. Wrap all code in <code> tags. Learn more.



Previous post: Stupid WordPress Tricks

Attention: Do NOT follow this link!