This will do you fine these days (IE 8 and up):
.group:after {
content: "";
display: table;
clear: both;
}
Apply it to any parent element in which you need to clear the floats. For example:
<div class="group">
<div class="is-floated"></div>
<div class="is-floated"></div>
<div class="is-floated"></div>
</div>
You would use this instead of clearing the float with something like <br style="clear: both;" />
at the bottom of the parent (easy to forget, not handleable right in CSS, non-semantic) or using something like overflow: hidden;
on the parent (you don’t always want to hide overflow).
Now for a bit of history!
This was the original popular version, designed to support browsers as far back as it possibly could:
.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 */
There then was a bit of a cleaner version documented here by Jeff Starr, 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 */
Then it became popular to use “group” as a class name, which is nicer and more semantic (via Dan Cederholm). Also, the content
property doesn’t even need the space, it can be empty string (via Nicolas Gallagher). Then, 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.
.group:before,
.group:after {
content: "";
display: table;
}
.group:after {
clear: both;
}
.group {
zoom: 1; /* For IE 6/7 (trigger hasLayout) */
}
See the top of this page for the most modern version of the clearfix.
In the future, we might be able to do:
.group {
display: flow-root;
}
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.
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. :)
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.
lol just so you’re “clear” haha :)
I’m only using, and i diden’t see errors on testing websites.
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.
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.
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.
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 !
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!
You’re the worst person I’ve ever met.
Then you woke up and realized who cares.
Wow, that Maggie Wolfe Riley, she’s incredibly patronising, isn’t she.
Had to double check my apostrophe usage there.
How do you sleep at night? What a stupid comment, we all knew what he meant.
it’s quite funny that he’s actually changed hi’s title’s hahah
Maggie Wolfe Riley probably has a lot of cats.
Thank you Maggie! Very helpful.
I hate people like you!
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;
SOMETHING, ANYTHING.
You aren’t the only one. I like the third one the best.
Aaaaagreed.
Yes! Long overdue!
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.
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
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.
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.
Clearfix completly doesn’t work on IE7 for me, it fixed IE6 issues, but not IE7, any ideas?
I’ve just found this site
http://wiki.fluidproject.org/display/fluid/Testing+clear-fix+solutions
where all the clearfixes are tested, it seems like on IE7 none of them works :( bizzare. Has any one got any solution to this?
May 18th Update:
Isn’t “display:table” usually discouraged? or is it ok here because it is applying it to the “content:”” “?
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!
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 http://jsfiddle.net/. All the techniques have multiple selectors, the ones without pseudo elements are for IE 6/7.
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…
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.
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! :)
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.
Thanks for the explanation Kristian. Until now, I also had a hard time finding a clear answer.
Hi! Due to last update: Parent elements with ‘display:table’ don’t mess out their absolute positioned child elements?
Very nice how you display the uptates of the fix. This way it’s really easy to see the development of it! Thanks!
Clearest article on the Clearfix hack yet.
Outstanding work on this site’s graphics.
Bravo!
Totally agree~~
Overflow is the missing ‘chink’ [thanks, Patrick, you old Dog] …
CSS3 parenting [CSScube] semantic ever since IE4-6, Opera.fun 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
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
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.
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!
I love your site, but it would be simpler if you offer only one working clearfix snippet instead of two or three.
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.
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
Same happening here. Firefox is having problem with Nicolas’s clear-fix. What to do?
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.
Something that always works for me rather than using clearfix is to have a simple calss in your css file:
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.
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.
Seem to be fake hugo g
Hi,
I love the micro clearfix hack, and find it very appropriate when writing modular CSS. Just add a .cf class to the element you’d like to clear and your done! Also, using this as a mixin when using LESS or SCSS is a breeze.
Still – a discussion with a colleague made me think. How is using pseudo :before/ :after affect memory usage when the browser renders the page?
Using content: “”; in your CSS does not insert anything into the DOM-tree, but they are being rendered into the render-tree, right?
Let’s say you have 1000 elements, all with the clearfix applied. The browser actually has to handle the :before and :after as well as the main element (visually). The issue arise when discussing optimization for mobile browsers. Usually they perform slower than desktop browsers.
If the traditional overflow:hidden can be used to clear elements (and your design let’s you use this), isn’t this better performance-wise?
Great thinking. I suspect that even mobile browsers handle it pretty blazingly fast, but it would be worth some tests. Too bad CSS testing like that is so difficult.
It seems unlikely that you would need a clearfix applied to so many elements on one page? if you do, perhaps before worrying about if that would bog down a browser, then perhaps you should also work on writing simpler layout HTML and CSS that wouldn’t require so many clearing events to be required to make everything go where it needs, as such a complicated or redundant pile of layout code will also be bogging down the browser.
overflow:hidden and overflow:auto have the occasional problem where they either a) hide stuff that you don’t want hidden, or b) show scroll bars sometimes if things get a little off. Neither of these is optimal in my book, so these clearfix hacks are the preferred method. There is a reason people like Chris and Nic Gallagher promote these solutions — from a layout/design perspective they are reliable and have less adverse affects than the alternative.
I never get this to work no matter what … Ah well, let it overflow
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).
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.
function example() {
element.innerHTML = “code”;
}
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?
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 addfont-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 :)
http://www.jqui.net/tips-tricks/css-clearfix/
The last example (august 2012) doesn’t work in Safari 6.0.1
The previous one works perfect. Thank you!
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.
I tried to validate this CSS by http://jigsaw.w3.org/css-validator/. 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;
}[/code]
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.
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.
i can’t seem to get a desired result with this technique (although i remember it used to work for me as expected).
http://jsfiddle.net/92wmB/9/
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>)
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.
Wait for flexbox
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.
Why is it that you are still suggesting
table
when you Nicolas said that the use oftable
was due to :before.Did I miss something?
Hi!
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)
Thanks.
The
p
element inside of theli
needsmargin-top: 0;
The first
p
needsmargin-top: 0;
and the 2nd (last)p
needsmargin-bottom: 0;
here is the fixed version
Hey, Adonis K.
Updated jsfiddle
I added a background:skyblue to the “ul” and background:darkgrey to the “li”. Can you see the skyblue background right after the darkgrey background?
That skyblue background below the darkgrey li shouldn’t appear, right?
I’m a bit confused with all the updates. Is the one on top the most recent or the bottom??
Me too.
yeah which one should I use?! O.o
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 CodeSchool.com 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.
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?
Thanx!
pseudo-elements ::after and ::before requires the property “content”, otherwise they’ll be ignored
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?
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.
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!
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.
Hahaha. I love to see the progress with the updates!
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.
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.
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.
mehn you’re Godsent……ve been looking for this for long
You saved my life with this!
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? http://www.eweknit.com/photos/
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?)
?
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)
This what I’ve been using with SCSS.
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.I don’t see how the IE6/7 lines help, as IE7/earlier doesn’t support either :after or :nth-child, so it will be ineffective.
With such browser issues (yes, we still need to support IE7 in 2015), is it much less clean to have
<div class='clearfloat'/>
after, thanclass='superlativeclearfloat'
in the element, with a bunch of mysterious CSS…?Why don’t you just use…
overflow: auto;
zoom: 1;
Hi Chris,
I noticed you didn’t include the :before on the last update. I haven’t been including it either and it’s been working so far as intended, but will I find later on that I should include it?
Thanks,
Justin
Please note that pseudo elements are written using TWO colons (as opposed to pseudo classes, which are written using a single colon). So
.clearfix:after
should read
.clearfix::after
Göran is correct for everything IE9+ and modern.
IE8 only understands the old single colon syntax. Include a single colon version as well if you need IE8 support. It’s not ideal but we’re talking about a hack in the first place.
I think we have a better solution in the intrinsic and extrinsic sizing module on the way but it’s support won’t be good enough for most projects for some time http://caniuse.com/#feat=intrinsic-width
Is there a problem with just using display: table? Sorry I can test this on order or mobile browsers.
Jens Meiert (the Google frameworks developer) wrote about clearfixes just the other week and suggested just to use overflow. https://meiert.com/en/blog/20161114/no-clearfix/
I believe adding a picture would make it easier to understand what the article is talking about. This helped me:
http://stackoverflow.com/questions/8554043/what-is-a-clearfix/29562362#29562362
What about
overflow:auto|hidden
(on parent container)…?How about:
Thanks Rob. I like this a lot. And it works as expected on all browsers that I’ve tested.
However, depending on the structure of your html, the .clearfix {display:flow-root;} solution seems to handle margin collapsing differently to the .clearfix::after {content: “”; clear: both; display: block;} solution. So, it’s best to thoroughly check the margin collapsing on all required browsers when using this solution, to be sure it meets the desired outcome.
There is some discussion about the clearfix::after solution and margin collapsing at http://www.cssmojo.com/the-very-latest-clearfix-reloaded/.
In my case, with my chosen layout methods and the need to accommodate IE11 as well as modern browsers, I stick with the .clearfix::after solution. I look forward to the day when display:flow-root is all we need.
I never understood why people uses a “clearfix” hack.
I was always under the assumption that you should never leave a
<
div> without CSS properties.
I never used this “clearfix” thingy on my website, and I always got exactly what I wanted,
Just don’t assume the browser knows what you wanna do with your html elements,
and so don’t leave your element styling to luck and you’ll be fine!!
My shorthand “clearfix” is the following, unless you want to “clearfix” the very last element in a container:
Hi Chris! Man I have always been a fan of your work. You have great info, and you really make it an awesome learning experience. I am realizing that your posts go back to 2009. That’s amazing! Do you still post here? Just wondering because I am still reading and learning,and oh practicing too. Thanks JP Olivier
I learned somewhere that the parent as inline-block is the correct height for floated children.