Treehouse: Grow your CSS skills. Land your dream job.

Last updated on:

Force Element To Self-Clear its Children

A.K.A The "Clearfix" hack.

.clearfix:after {
     visibility: hidden;
     display: block;
     font-size: 0;
     content: " ";
     clear: both;
     height: 0;
.clearfix { display: inline-block; }
/* start commented backslash hack \*/
* html .clearfix { height: 1%; }
.clearfix { display: block; }
/* close commented backslash hack */

Just apply a class="clearfix" to the parent element. This is an improved version of the original, and documented here.

Updated by Jeff Starr to be cleaner, based on the fact that nobody uses IE for Mac, which is what the backslash hack was all about.

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

Updated again... "group" class name is nicer and more semantic (via Dan Cederholm). Content property doesn't even need the space, can be empty string (via Nicolas Gallagher). Without any text, font-size is un-needed (Chris Coyier).

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

Of course if you drop IE 6 or 7 support, remove the associated lines.

Update May 18, 2011: Nicolas Gallagher again with the "micro" clearfix. Also see this additional stuff.
.group:after {
    content: "";
    display: table;
.group:after {
    clear: both;
.group {
    zoom: 1; /* For IE 6/7 (trigger hasLayout) */

Update August 2012: I'd say for the most part these days (if you only need IE 8 and up) this is fine:

.group:after {
  content: "";
  display: table;
  clear: both;


  1. Permalink to comment#

    just so i’m clear: would this be for child elements that are floated, and thus the parent element disappears?

    i’ve found that applying overflow: hidden; to the parent element takes care of this. the parent element then fills in behind the child elements.

    • Yes that is right, but overflow: hidden; also hides the overflow, which may be undesirable behavior in some circumstances.

    • Permalink to comment#

      overflow: auto;
      works well as long as you are able to keep control of your margins and padding (else you see scrollbars). That’s ironic. :)

    • Deepak

      Chris Coyier said: Yes that is right, but overflow: hidden; also hides the overflow, which may be undesirable behavior in some circumstances.””

      Quick links menu, ul,li used custom select list etc (those are absolute positioned) are the some circumstances.

  2. I still use this religiously. I rarely fails me and has worked cross browser extremely well.

    Only time I get a hiccup with it is when I had a fluid container that was floated left or right. I would get a large gap underneath one of the elements when clearfix was in place.

  3. Permalink to comment#

    Rocking ! I ve always had a confusion on judging whether to use the markup based clear or this one. This is cool … but still have to test it in a pretty bigger application.

  4. Permalink to comment#

    Im concerned about the .clearfix{display:inline-block;}, block. Im not sure if this would be 100% perfect in a application of a high volume of markups / complex layouts. Correct me if wrong.

  5. Permalink to comment#

    The edit and delete functionality of this comment section just rocks :). Im loving the counter … great user experience and awesome interaction design. Keep it going chris !

  6. Chris – you, like Mary Poppins, are practically perfect in every way, except for it’s and its. So in order to help you attain a higher level of perfection, I am going to give you a free lesson!!!! (are you excited yet?)

    Possessive pronouns: his, hers, theirs, ours, mine, yours, whose, and its
    Notice no apostrophes on any of those – just think “his, hers, its” to help you remember that.

    Contraction: It is shortens to it’s, he is => he’s, she is => she’s, I am => I’m, you are => you’re, they are => they’re, we are => we’re, who is => who’s

    For pronouns, the only apostrophes are for contractions as shown above. Regular nouns do use apostrophes to show possession but not pronouns.

    So your title for this post should be “Force Element To Self-Clear its Children” (not it’s). I see this mistake a lot in your posts, but this one stands out even more since it’s in the title.

    Whew! That out of the way (and seeing those errors really does get in the way of content), you are awesome and I have learned SO much from you – I hope my little grammar lesson actually helps!

    And, on topic, thank you for THIS helpful snippet!

  7. thinsoldier
    Permalink to comment#

    Am I really the only one who things there should be a standardized non-hack way of doing this added to CSS3?

    Really? I’m the only one? (sad, slow facepalm)

    overflow: evelop;
    overflow: contain-floats;
    float-collapse: none;


    • Steven
      Permalink to comment#

      You aren’t the only one. I like the third one the best.

    • Jason
      Permalink to comment#


    • Harry Pujols
      Permalink to comment#

      Yes! Long overdue!

    • Mark Stickling
      Permalink to comment#

      A native property would be very welcome.

      I can’t find any useful explanations when I google things like “why is there no native clearfix in css”.
      Anyone know why?

      Flexbox was driving me mad the other day as I was using justify-content:space-between; and it was including the invisible pseudo elements in the calculations. It’s simple to remove them again using modernizr as a hook but it’s just hastle.

  8. This can be a dangerous technique to use unless authors know exactly what this styling means in term of construct.
    See everything you know about clearfix is wrong

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

  10. Permalink to comment#

    Wow. This is hands down one of the best designed websites I’ve seen. Everything is beautiful, loads quick, and has just the right amount of interactivity and minimalism.

    About this post, I’m new to CSS, and this problem had me puzzled for a while, till I learned that a thing like a clearfix hack existed from a TutorialZine template. I can’t believe that so many people, for so many years, have pointed out this problem, and it still hasn’t been fixed. Semantic tags like nav and section mean little when more basic problems such as this are not addressed. I find the whole designing by CSS technique very tedious, I can’t blame developers for using tables in the past.

  11. fanta
    Permalink to comment#

    Clearfix completly doesn’t work on IE7 for me, it fixed IE6 issues, but not IE7, any ideas?

  12. fanta
    Permalink to comment#

    I’ve just found this site

    where all the clearfixes are tested, it seems like on IE7 none of them works :( bizzare. Has any one got any solution to this?

  13. Ash Clarke

    May 18th Update:

    Isn’t “display:table” usually discouraged? or is it ok here because it is applying it to the “content:”” “?

    • Permalink to comment#

      Html tables are for tabular data and too use them for layout is semantically wrong. CSS is not about semantics but presentation.
      So presenting an element as display:table or display:table-cell or whatever is just dandy!

  14. stope
    Permalink to comment#

    I am pretty sure that :before and :after pseudo-selectors don’t work in IE6 and IE7, so this solution isn’t useful regarding cross-browser functionality…

    Any further comments on the matter?

    • It does work. Try things before crying foul. It’s very easy to throw together tests in All the techniques have multiple selectors, the ones without pseudo elements are for IE 6/7.

    • stope
      Permalink to comment#

      Sorry, I was talking about the last one. The only line without pseudo element is that one triggering hasLayout for IE. I’m surely missing something important or is this one working as clear:both for IE…

  15. I’ve been using this for years now, and it hasn’t failed me once. But it amazes me how people still have difficulties grasping this concept when they are UI developers. I had to teach this to a programmer of 15+ years recently, and still they are cloudy with the understanding of it.

    One of the best examples I show them is with background colors for parent, and separate child containers. That usually clears things up almost immediately with the difference between using clear fix and not having it applied.

  16. Jeffrey Bennett
    Permalink to comment#

    I probably *should* know this, but what exactly IS a clearfix and what is it’s purpose? I’ve searched all over for an explanation, but I couldn’t find anything on what they are. Thanks for your help! :)

    • Permalink to comment#

      when you use floating of elements the parent element no longer tries to wrap said element. When using a ton of floated elements all as part of a layout you sometimes have to “clear” the floating children so that the parent can continue to fully wrap them as desired maintaining the proper flow from a layout/design perspective.

      the .clearfix or .group classes when used with the above solutions provide a modular way to add this to a parent element with CSS and a class and not have to resort to adding non-semantic divs or breaks to your HTML.

  17. Permalink to comment#

    Hi! Due to last update: Parent elements with ‘display:table’ don’t mess out their absolute positioned child elements?

  18. Bnibbler
    Permalink to comment#

    Very nice how you display the uptates of the fix. This way it’s really easy to see the development of it! Thanks!

  19. Andy
    Permalink to comment#

    Clearest article on the Clearfix hack yet.
    Outstanding work on this site’s graphics.

  20. Overflow is the missing ‘chink’ [thanks, Patrick, you old Dog] …
    CSS3 parenting [CSScube] semantic ever since IE4-6, is simply

    overflow: auto

    In context, it’s [sp. for ms. Lady things]

    .cleargroup, parentname.cleargroup {
    display: block;
    font-size: 0;
    overflow: auto;

    And then, since we’re taking this to the nth degree

    .cleargroup:after { 
    display: block; 
    content: " "; 
    clear: both; 
    font-size: 0; 
    position: relative; 
    .cleargroup:after, *.cleargroup<parentname.clearfix { 
    position: relative; 
    visibility: visible; 
    zoom: 1;

    Font-size is the display element spacer, not height. Attribute font-size is the logical display anchor, and it’s value will be ignored (selector not required in new browsers? oh dear, anchor!). Echoing display:block in the attribute is critical to manage fluid float overflow inside cleargroup, with an absolute position. Relative positioning handles any CSS widgets you may throw into the cleargroup zone. For those still hobbled with old IE and Firefox foibles, the <operator cache helps; operator is ignored by others. Similarly, visibillity (loosen your collar, scriptites) is managed by display:block being attached to parent and child, securing attribute operator overflow in display as required.

    This runs especially well where build includes side-by-side vertical columns that wrap around a floated element or block. Parentname allows inclusion of an opening blockquote salvo, or whatever. A closing salvo, however, would slightly screw your float wrap, inline or otherwise. Because there’s no overflow left over. It’s one of those characteristic CSS logical die-out things, Ugh.

    Now, the design and development question is inside of parent or outside of predecessor. On page, in new browsers it seems a non-challant either-or div. Which leaves the style cue open for scripting and devicing. For the pure at heart, there’s also cleargroup container popup tutorials. In that scenario, overflow balances clip margins, etc.

    ergo: hope those awesome “echo” and “zone” terms in the vicinity of any CSS attribute don’t upset designers out there. The hermeneutic envelope that secures CSS discourse is not quite secure, is it? Net5 and CSS4 are on the move. … overflow:auto

    • nnif semaj
      Permalink to comment#

      What in holy hell are you talking about. I hate pseudo-intellectuals.

      (Sorry, I just had to say that. It sounded funny and fit in perfectly at this juncture)

      pseudo-intellectual: a person who attempts to pass themselves off as above the average intelligence by assuming their chosen vocabulary will confuse most people. The desired effect being: “Wow, he sounds smart!”

      [my definition]

      OK. I should stop now.

      BTW – your site rocks Chris. Many blessings.

  21. Permalink to comment#

    I love this approach. The group class has now completely replaced clearfix for me. You’ll never see a clearfix class name in my work again. Awesome as always, sir!

  22. Chris Hu
    Permalink to comment#

    I love your site, but it would be simpler if you offer only one working clearfix snippet instead of two or three.

    • Permalink to comment#

      You should just use the last one then, as long as it’s okay that it only works in IE8+ — what he’s showing you here is the evolution of the hack, and the 2nd to last iteration is the most advanced one that still works everywhere… there you go.

  23. Sebastian
    Permalink to comment#

    Thanks Chris for your clearfix-snippet! Still working great. I was using the micro-fix from Nicolas that comes along with Pauls Boilerplate, but in the newest Firefox it broke my layout and behaved unexpected. Yours is still working, niceOne on this :D

  24. Hi Chris,
    I think there is currently a bug in Firefox that if you don’t have anything in “content” then form elements get double margin. I’m positive that even a space doesn’t work and FF needs at least a dot. Haven’t noticed such behavior with other elements.

  25. Permalink to comment#

    Something that always works for me rather than using clearfix is to have a simple calss in your css file:

    .cleared{width:100%; clear:both;}

    Then just stick a div with the above class element below all your floated ones

    Never had an issue with it unlike the clearfix solution.

    • Adding markup to fix styles issues is not a good idea (even if it is possible indeed) simply because markup is supposed to have semantical reasons, without any style / design implication.

      You can add a <div> (or a <hr> or whatever) to fix floats issues, and it has been done for a long time, but it adds avoidable elements to the DOM tree, and it uses the markup on a wrong purpose.

      Moreover, it is easier to have a class to apply to the element which needs a clear fix than adding a non semantical element before the close tag of the element which needs a clear fix.

    • Kippy
      Permalink to comment#

      Well geezuz for a minute there I was feeling a little on the stupid side. I use this as well. Thanks for posting. It saved my sanity.

    • Dhc
      Permalink to comment#

      Seem to be fake hugo g

  26. Arie Putranto
    Permalink to comment#

    I never get this to work no matter what … Ah well, let it overflow

  27. Derek
    Permalink to comment#

    Using the universal selector (*) has pretty severe adverse performance implications. Adding single top-level wildcard to your CSS like you’ve shown will usually at least quadruple your CSS parse time in my experience. Better to use IE conditional comments for the IE specific stuff so that you don’t slow down everyone else’s browser (not to mention that it’s not a hack, but a supported feature designed to do exactly what you want to do that you can rely on).

  28. Using the universal selector (*) has pretty severe adverse performance implications.

    Do you have some real data on that? I’ve literally never seen data to that effect. I know that, technically, yes, that selector is going to take long to parse than an ID selector, but is it literally a delay that you can feel? My hypothesis is that it’s not a big deal you either have a page with WAY more elements than an average site has or you use TONS of universal selectors.

  29. Ro-kyu
    Permalink to comment#

    In the last example you can also use display: block; instead of display: table; and it will work the same. Is there any difference between them? Like, does it matter which one to use?

  30. Permalink to comment#

    I think you could improve this by changing the content info this .clearfix:after { content: "0A0";} which basically it will change it to a white space also you could add font-size:0; to remove the unnecessary line at the end of the element it will align properly :)

    Thank you so much for this:

    I took this idea from this website, hope it helps :)

  31. Davinmsu
    Permalink to comment#

    The last example (august 2012) doesn’t work in Safari 6.0.1
    The previous one works perfect. Thank you!

  32. Jerry
    Permalink to comment#

    Compatibility Issue : ?

    I don’t know if you’ve tried looking at this site using
    Opera 12.02
    Build 1578
    Windows 7 ( 32 bit ),

    but the CSS snippets, don’t look good at all.

    The snippets require the user to scroll horizontally to view the whole snippet, which makes it hard to read.

    I tried this on Chrome and it works as expected but Opera puts it all on 1 line and adds a left-right scroll bar.

    Very unpleasant for us Opera users. I just wanted to let you know in case it matters to you.

  33. lalit bisht
    Permalink to comment#

    I tried to validate this CSS by It found just one error: zoom property not exists for element * + html .clearfix. It seems like this issue could be fixed by replacing following base.css file fragment:
    [code=css]/* for IE7 */
    * + html .clearfix {
    zoom: 1 !important;

  34. JTM
    Permalink to comment#

    Has anyone had chunks of web pages disappear on Chrome but not other browsers? The missing chunks load if I stretch the browser window to the right. They seem to appear right after the second div on a page that has the “group” class (the WP e-commerce plugin applies the group class to each product div on the products page). I’m wondering if having the group class many times on a page is a problem in Chrome.

  35. JTM
    Permalink to comment#

    I’ve played with this on several computers now, and I think the blank spaces are appearing in more random patterns then I thought. I don’t think it has to do with the “group” class. However, if someone wanted to answer the question of whether assigning the group class to several divs on a page was an issue, that would be good to know. Thanks, everyone.

  36. ips
    Permalink to comment#

    i can’t seem to get a desired result with this technique (although i remember it used to work for me as expected).

    Unfloated elements still wrap around the floated and “self cleared” elements. I’d expect even unfloated elements to respect the pseudo element’s clearing rule. As you can see in the fiddle it does work with the extra mark-up method (using <div style=”both”></div>)

  37. chris
    Permalink to comment#

    The real problem here is that we are using floats on block elements that shouldn’t have the float at all.

    The only real solution i can see to remove need for hacks like this would be for CSS to implement a method to properly handle floating of block elements.

    Considering the slow progress of CSS to date, i won’t be waiting on that happening any time soon.

  38. Excellent. I am particularly fond of the last update from August 2012. Finally a clearfix I was able to learn by heart. I have already used it very successfully with my students. Thanks a lot.

  39. Why is it that you are still suggesting table when you Nicolas said that the use of table was due to :before.

    The use of table rather than block is only necessary if using :before to contain the top-margins of child elements.

    Did I miss something?

  40. dork
    Permalink to comment#


    I tried applying the latest version of clearfix/group here: jsfiddle link.

    How come there’s an extra space after the “li” tags in the feeds “ul”? When I used the original clearfix version, there’s no space there. (Chrome, Firefox, IE)


  41. stephan

    I’m a bit confused with all the updates. Is the one on top the most recent or the bottom??

    • Vikram
      Permalink to comment#

      Me too.

    • Scoreggio
      Permalink to comment#

      yeah which one should I use?! O.o

    • Adam
      Permalink to comment#

      I believe the second-to-last one is the most recent “update” to the clearfix (and you can use the last one if you don’t support IE6/7). I know that doesn’t seem right as the date on it says August 2012 but I am going through and that is what they are using. Also, he mentions how he updates to using .group instead of .clearfix which would nullify any which use clearfix as the class name. You can see that it is also more simple than the others which, I’m assuming would mean that it is more relevant as things tend to get simpler over time.

      Could be wrong but that is just my two-cents.

  42. sunchild
    Permalink to comment#

    Hi everybody, I still don’t really understand the solution.

    Why the neccesity for: content: "";
    Is it because the browser wouldn’t acknowledge the appended element, it being empty.. or something like that?


    • ngwdaniel
      Permalink to comment#

      pseudo-elements ::after and ::before requires the property “content”, otherwise they’ll be ignored

  43. Bryan Rayner
    Permalink to comment#

    Has anyone suggested a display:clearfix rule or equivalent to the W3C for a new standard of CSS? It’s crazy that we have to use a hack just to get functionality that should come as a built in option.

    How do we even suggest such a thing?

  44. A humble Brazilian.
    Permalink to comment#

    What’s up everybody?!

    I’ve been looking in the entire internet to solve this bug with firefox. My site presents perfectly in chrome, I.E., but firefox was blank (yea, nothing inside the “container” appears in screen).

    The Solution: #contaier {overflow: auto; clear: both;}
    obs. “container” is the ID name of the main div in my site.

    Problems I had:
    Adding a div with the property “clear: both” inside the container worked until I realized that my “border-radius” disappeared.
    “Overflow: visible” (only) showed the elements, BUT the background color also disappeared.
    “clear: both” (only) also doesn’t show the background.

    For me, this worked very well.
    I really hopped to explain more about this issue, but my English is not so good for that.

  45. Jean-Francois
    Permalink to comment#

    So basically if I have layouts that uses wrappers, I just add the class “group” to all my wrappers?
    Are they needed on ul lists as well just to be on the safe side?
    Btw chris your videocasts are truely amazing!

  46. Tim
    Permalink to comment#

    Suggestion for this page: Should we invert the order of the fixes so that the most recent is shown first? I think that’s what people most want, and they can scroll through the history as required.

  47. FYI, some earlier comments (from waaaay back) linked to a page, “Best Clearfix Ever.”
    The link was broken. I used a little Google-fu to track it down.

    The correct link: Best Clearfix Ever

    • I like their approach, but it could be done better. They have a lot of repeated styles, and everyone knows that isn’t DRY at all. Haha.

  48. chris.

    All kudos to the author, but the point of css is cut out redundant styling. So their version while it works great would be better like this.

        `/* our Global CSS file */
        article:after, aside:after, div:after, footer:after, 
        form:after, header:after, nav:after, section:after, ul:after {
            clear:both; content:".";
        /* our ie CSS file */
        article, aside, div, footer,
        form, header, nav, section, ul {

    No need to repeat the same line over and again for each element to clear right? now that is some nice automatic clearing right there. Excellent.

  49. Joe Cool
    Permalink to comment#

    You saved my life with this!

  50. Randy
    Permalink to comment#

    I must be misunderstanding something, because although it looks great at first glance… my images overlap in the lower part of the Div where you need to scroll up to view them. Does anyone know how to prevent this?

  51. Permalink to comment#

    What is wrong with the shorter versions I see around like:
    .cf:before, .cf:after { content: “”; display: table; }
    .cf:after { clear: both; }
    .cf { zoom: 1; } (with the demise of IE 6/7 this can be dropped right?)

    • Permalink to comment#

      That’s not any different than the last one chris lists — but you can name it whatever you want.

      .group::after {
      content: "";
      display: table;
      clear: both;

      This post just has all many old iterations to show you how clearfix has evolved… and to show you the simplest, newest form in its shortened glory

      (Actually, Chris’s is different in that it only includes ::after, so renders 1/2 the objects into the DOM)

  52. Dustin
    Permalink to comment#

    This what I’ve been using with SCSS.

    @mixin clearfix {
      clear: both;
      &::after {
        content: '';
        display: table;

    It’s a mixin because you can’t extend a placeholder class over media queries in Sass. I do it this way to keep my HTML clean.

    I’m not sure why the clear: both was always in the ::after, but that didn’t work all the time for me. I haven’t had any problem putting it in the actual element though and it seems to work in all cases I’ve tested.

Leave a Comment

Posting Code

We highly encourage you to post problematic HTML/CSS/JavaScript over on CodePen and include the link in your post. It's much easier to see, understand, and help with when you do that.

Markdown is supported, so you can write inline code like `<div>this</div>` or multiline blocks of code in in triple backtick fences like this:

  function example() {
    element.innerHTML = "<div>code</div>";