One of the hurdles (and “ah-ha” moments) in learning CSS is this business about clearing floats. If you have no idea what I’m talking about, check out the classic All About Floats.
I specifically want to talk about the issues of “collapsing”, that is, how elements that contain floated items don’t take those floated items into account in calculating their height. For example a parent element that only contains floated items will have a zero height. This is surprising and confusing to those new to CSS, and seems to be counter-intuitive.
Solving it is typically trivial. Using any overflow value of hidden or auto on the parent will “fix” it. The clearfix is also popular.
But these “fixes” give rise to the thinking that this behavior is “broken”1 to begin with. Confusing? Sure. Should be better options for control? Absolutely. Broken? Not really. If all containers expanded to contain their floated decedents, we would be complaining even worse, and the problem might be harder to work around.
The classic example
We’ll use this example presented by Eric Meyer seven years ago.
<p>
...text...
<img src="sunset.jpg" class="callout" />
...text...
</p>
<p>
...text...
</p>
The callout class, for example, would float the image to the left and apply some margins. This is what we get now:
That is exactly what we would want, the correct text reflow. In order for that to happen, that upper paragraph needs to “collapse” as it were, and let the floated image stick out of the bottom of it.
If the upper paragraph automatically expanded to contain the float, we’d be left with this:
As Eric said:
That’s something designers would never have accepted.
And I agree. This could have been an even worse problem, assuming no fancy workaround could have been found to work around it.
Should there be a better solution?
Yeah, probably. I’ve seen suggested:
overflow: contain;
That might work, but what about if you wanted to hide horizontal overflow? We already have overflow: hidden, which already contains floats, which works, but then that’s a bit semantically confusing. There could be a whole new attribute like
contain: floats | collapse | inherit;
But I dunno, they can’t just go adding new attributes all the time, so that would have to be taken under serious scrutiny.
1 I’d also like to add here that I hear people say that “floats take the element out of the document flow” fairly often, which isn’t true. Floated elements still affect inline elements (that’s kind of the point) as well as other floated block level elements. If floated elements were “removed from the document flow”, they wouldn’t affect anything (like absolutely positioned elements).
Aren’t we just abusing the float property for use it wasn’t intended? Maybe there should be a layout-flow proterty which does automaticly clear itself. The clearfix class is useful, but not the most elegant solution.
There seems to be a lot of HTML and CSS that we abuse in ways it wasn’t intended because it’s the only good way to do what we need.
Yes, that’s exactly what I think. It doesn’t seem that floats were originally meant for layouts because of the many problems that come with it – clearing, equal height, bumping down, etc, so many “fixes” have been made. Tables do seem much easier in many situations, but they aren’t meant for layout either (for good reasons).
It looks like there was some suggestions to incorporate more layout-based css: http://www.w3.org/TR/2009/WD-css3-layout-20090402/. It doesn’t look perfect, but it might be better than what we have now. But who knows when this would become a standard…
No, we are not abusing float. It is impossible to abuse presentation layer to describe presentation.
Best idea i heard today!
May as well submit this idea to the w3.
“Solving it is typically trivial. Using any overflow value of hidden or scroll on the parent will “fix” it.”
Overflow:auto is the proper solution here.
Yeah I meant to say “auto” there. But actually, I use “hidden” more than I use auto in situations I use this. It depends on context, but hidden I find a bit more bulletproof for IE6-land, when you aren’t setting a fixed height, so are just preventing things sticking out horizontally and screwing up layout.
Good thoughts! I have always want just a quick HTML non-terminating tag to perform clears. Like a “clear” tag, then “rtclear”, and “ltclear”…etc. However having it in the stylesheet as you mentioned above would probably be a more flexible fix.
I use a method I got from Ed Elliot, which always works for me.
Just add the container class to any div you want to contain all it’s contents, and it just works… It does mean adding a class to the HTML, but for me that’s more semantic than adding a clearing <br /> or whatever.
But a lot less semantic than just using overflow: auto;
This is usually what I like to use but the :after pseudo-class doesn’t work in most older browsers.
Isn´t it the first part of the “clearfix” technique?
Yeah, that’s just the clearfix
I say this a lot on these “css for newbies” type blog posts (and there are lot of them today) –
1. It is GREAT that people are writing on these topics for the “younger” generation of web designers who weren’t learning this stuff when it was FIRST written about by the actual technique inventors / innovators.
2. That said, let’s just be fair and give proper credit where it is due… the so-called “clearfix” approach was first widely documented and popularized by the good folks over at Position is Everything – http://www.positioniseverything.net/easyclearing.html
Keep on learning – it’s great stuff.
I’d go further in terms of a css fix. One issue I encounter frequently is an item in a side column intruding into a center column full of text, and the designer expects the text to wrap around the item. (Imagine the example above, but the image sticks out to the left.) I get this a lot from designers who are used to doing print. (I started in desktop publishing as well.)
In a page layout program, you can take an element, an image, let’s say, and apply text wrap to it. This means that anywhere you put the element on a page, if it intersects any text box, the text will get out of the way, and wrap around it. Designers expect this behavior from HTML pages, and I have to explain that it doesn’t work that way.
For text to wrap around an element in HTML, the element has to live inside the text. For the example above, the image tag is actually in between the words “egestas semper”. For the image to be left-aligned in a column to the left of the text, it has to have a negative left margin to pull it over. Which means it risks overlapping content in the left column.
I think maybe there needs to be a float:all or a text-wrap:left to handle this situation.
Wow Chris,
You mention it on the off beat, but JUST overflow:hidden (or auto) on the parent element as a 1 line working solution for float is insanely great.
Even the ‘easy’ float (clearfix/after + zoom:1 IE) is beaten by this.
I was (am) can’t believe this works in all “acceptable” browsers (IE6+, Mozilla FF2+, WebKit).
Thank you !
It is kinda nice, but the problem is that both overflow hidden and auto have very specific functions OTHER than fixing the float thing. Let’s say you have an image inside of a floated div that you INTENTIONALLY want to stick out past the width of the div (generally a bad idea, but stay with me). Overflow auto would trigger a horizontal scrollbar. Overflow hidden would cut it off. So, both of those options are out. But you still need to clear the float, so you are stuck with either adding an extra clearing element or the clearfix. There are other situations as well… the overflow thing is not ideal in general.
one could also float the parent element to achieve the same thing but without causing scrollbars or cutting the image off. google: “css shrink wrapping”
of course this isn’t ideal always either
Than it all depends of the situation that one encounters.
I use an extra clearing element when I have content hanging out of the containing div. Or, better, when the containing div is the main 960px wide centered container and I need the horizontal scroll bars to appear when the window is resized. The scroll bars wont show up if overflow:hidden is used.
Otherwise, I go with overflow hidden.
But never with overflow auto because it can lead to unwanted vertical scrollbars if extra content is added.
“I hear people say that “floats take the element out of the document flow” fairly often, which isn’t true.”
I hear this a lot too, and just accepted the statement until now. Now I’m not sure what to think. Even if floats don’t take the element out of the document flow…they still affect the flow of the document. Maybe rather than saying that floats take the element out of the document flow, it would be better to say they shift the element from it’s natural location and affect the position of the elements that follow it???
I think the confusion comes from the differences between the similarly-named “document flow” and “text flow”. See this section of the spec for more information:
http://www.w3.org/TR/CSS2/visuren.html#comparison
Finally! I very good explanation!
If you need the text to “collapse” then why not just clear right?
Ex: img { float: left; clear: right; }
The problem with adding new rules to CSS or adding new elements is clearly unaccaptable. If we’d do so, all current browsers would become obsolete and we’d have to add the current fixes as well as the “new” fixes untill 2018 when nobody uses IE9 anymore. That if W3C would apply the rules within 2010, which probably wouldn’t be the case. I don’t think we’re waiting to support a new rule and an old hack untill half of us is going to retire as a developer.
“but what about if you wanted to hide horizontal overflow”
A perfect use case for overflow-x and overflow-y.
I’m sorry if this is off topic:
I have a question regarding floated elements vs list elements (ul or ol).
If the list has list-style-position ‘outside’, the bullets won’t affected by the floating elements and will be placed behind it. Is there any workaround to this? Since using ‘inside’ position is not as neat as the ‘outside’.
good article this may help to many of my friends because they always made mistake of clearings…
I wondered why those posts left an unneeded gap. Good solution.
I think w3c disagree with you.
http://www.w3.org/TR/CSS2/visuren.html#floats
says:
“Since a float is not in the flow, non-positioned block boxes created before and after the float box flow vertically as if the float did not exist. However, line boxes created next to the float are shortened to make room for the margin box of the float.”
So you here are presenting pseudo-CSS?
I don’t think Chris is wrong, but I think further explanation is needed. As someone else pointed out, the “flow” being referred to is not “document flow” (as even I’ve incorrectly stated at times), but refers to the flow of block level elements. Inline elements will flow around floated elements. Even SitePoint’s reference doesn’t really make it clear whether they’re referring to “document flow”, using just the word “flow”.
So, you could say a float is taken out of “relative” flow, for lack of a better phrase.
I really believe that this here it’s made more complicated then it is. Floats are floats, box/element whateever. Floats should be used rarely.
Someone gave the simple and handy ideea for using floats in creating templates and it was quick to push forward. I really don’t find a normal use for float. It’s just habbit with some ppl and a trend I think it’s soon going down. Display and position are enough. Just need correct applying.
If you never use floats, and only use positioning, unless you’re a CSS super-expert, then you’re going to create unmaintainable website layouts. And I suspect that even if you’re a super-expert, you’ll still have trouble creating maintainable layouts.
how about “block-flow” and “inline-flow” as a distinction?
So float, an exeption in positioning, is your base for a css layout? I believe you just replace a bad style (table based) with it’s evil twin brother :)
That’s what table advocates are using to argue against CSS div layout.
One big reason floats are better than tables for layout, is that a table layout is non-semantic and confuses search engines and text-reader browsers, etc. Using floats, your HTML code can be structured properly. Anybody who tried to argue that floats are table’s evil twin does not understand semantics and coding standards, and I would guess is only an amateur designer/developer.
@ Richard of Norway: Two big reasons you are an amateur:
– you are using XHTML and that’s a tag soup for IE, the most used (like it or not) browser
– you’re http://www.richardharris.no/ page HTML it’s not more semantic using floats: you’re using a container div, a wrapper div before starting to put any SEMANTIC content.
I see you have table style code in your home page CSS, but it’s not used anymore, so I believe you just switched from them. You should definitively learn more CSS before making statements :)
Ulyses: tag soup apparently doesn’t mean what you think it means. That’s the most popular red herring of the last two years, so it’s understandable, but it’s still a red herring.
OK, it’s seems like you are making me here a bad guy. So let’s take it step by step. I don’t think that telling the truth about this article is bad.
The title, is a dud. I see here that somebody needs to go back to basics, and learn that even an inline box can be a container, and auto clear for an inline box is… stupid?
Then, the author, Chris Coyier, states that:
“I specifically want to talk about the issues of “collapsing”, that is, how elements that contain floated items don’t take those floated items into account in calculating their height.”
and then
“I’d also like to add here that I hear people say that “floats take the element out of the document flow” fairly often, which isn’t true”
which are in DIRECT CONTRADICTION. If elements were not taken out of the flow, that would not happen.
Another half true said here is the next one:
“For example a parent element that only contains floated items will have a zero height. ”
This is NOT TRUE if the parent is also floated.
Then, he goes on and says:
“Solving it is typically trivial. Using any overflow value of hidden or auto on the parent will “fix” it. The clearfix is also popular.”
and he doesn’t give credit to ppl discovering them, as pointed out better in this article from … 2005: http://www.sitepoint.com/blogs/2005/02/26/simple-clearing-of-floats.
Also he does not mention a VERY GOOD workaround (not hack) for clearing a float, that is “Floating nearly Everything” (FnE).
And finally, about your so called red herring, tag soup is EXACTLY what I think, but for you to learn. Need more details, I’ll provide you with the TRUTH. Even if IE’s user agent helps you when you write XHTML, you are not looking at a XHTML but a tag soup treated kindly as HTML, simply because IE doesn’t support documents served as application/xhtml+xml. I’ve learned it (the hard way) also thanks to http://www.sitepoint.com/forums/showthread.php?t=393445.
@Luis: it’s not maintanable unless it’s floating? Not a good concept.
Ulyses, can you show me a documented method for achieving a maintainable CSS layout that does not use floats? I’m not talking about one-off tutorials that demonstrate the *possibility* of a layout without floats. I’m asking you to show me in practice, where such a concept has been successful.
I’m not saying that a layout should be littered with floats. I’m saying that a few floats along with a good mix of positioning, plu heeding other cross-browser principles carefull will be the most viable solution. If you can provide some real-world evidence that layouts don’t require *any* floats, then go ahead, but I doubt you can.
Gimme a project and I’ll do it without floats. And a paid one would be nice:)
I have developed a number of templates, for printing or for screen, that don’t involve using floats. I don’t understand why you need them so much. A float you don’t need when you columns define:)
Just because w3cschools does teach you using floats for defining columns in your layout that doesn’t make it law.
@Richard of Norway: Say what? When you insert wrapper div’s for use with floats that makes your HTML semantic? You should check again:)
And your CSS is not at all what is supposed to be even if you help youtr HTML. A good developer tryies to make good HTML AND GOOD CSS. Maybe you are not one of them.
Ulyses, I’m not talking about what is possible. And in fact, I think it would be easier to create a layout without floats. That’s not the issue here.
The issue is whether or not a float-less layout is practical and maintainable in a real-world situation.
Well, I try not to use floats, and most of all not for the main layout. It’s an opinion and in practice it’s reliable.
‘Till now for me it is. Day come when not you’ll see me post here full details.
You are the one put in difficulty when you’ll have to switch from floats (like those that needed to switch from tables).
Floats just simulate a layout, layout that it is possible by other, more natural, more “CSS semantic” means.
It’s just basic CSS replacing your float habbits with the right ones. IMO :)
This guy is just a troll. Stop feeding him.
Please be so kind and explain troll :)
I feel crazy for saying this, but I actually wish floating objects did expand the dimensions of their parent container. I guess I think too “real world.” Like putting boxes in a garbage bag. You’d never expect the bags to phase through the physical matter of the bag’s walls. It would be cool if there were a CSS property we could assign to the parent element to turn on/off whether or not any floating children expanded it or not.
Problem is not the “float” property per-se.
In your example’s context – call out image, just like in print design – it works just fine. In fact, it’s the intended purpose of it.
You start having problems when you use “float” outside of this usage context. When you start using “float” to make columns, for instance.
It’s just counter-intuitive, because the “float” is a broken conceptual model for anything else besides floating a piece of content in the middle of a paragraph or other content flow that the browser engine knows how to “wrap around” the element.
Not to mention that float clearing behaviour is completly non-standard across browsers, and you can’t blame them. Each one will implement a different behaviour where the specs dont handle what should happen when different floated elements interact. It’s just impossible to find what’s is the “right way”, because, again, the conceptual model is broken.
That’s why it’s the major hurdle in CSS.
Excellent post. I agree with your take on floats. I believe the WC3 imagined a way of replacing align=”right|left” in images with a css alternative. I don’t think they thought it through well enough, but since I was not a part of the discussions I can not imagine how difficult it must have been, and I won’t judge them. I merely look forward to the day when these types of problems are behind us. :)
I agree. Float it’s a wrong tool to… position. That’s why there are css properties like display and position.
Excellent explanation. This is something fundamental that a lot of newbies can’t get their heads around for a while.
I think the only problem here is that the clearing methods are labeled “fixes” which as you say suggests that something is broken.
Nothing is broken, nothing needs to be fixed, it just needs to be cleared.
Going to much “float” after leaving behind to much “table” it’s just as big CSS sin.
Float gore not good CSS practice.
IMO.
It’s like the battle for semnatic HTML. How ’bout semnatic CSS?
I agree, its just not intuitive!
Nice article Chris,
I’ve found the best way to make a container stretch to the height of it’s floated contents is to also float the container.
This is how my equal height columns method works.
To those of you arguing against the use of float for layouts, what would you recommend instead? display and position can only get you so far. What if you…
actually, the more I try to think of a situation where float is the only solution (and do some quick research into the options so I don’t look like an idiot) The more I realize not using floats but maintaining flexibility is something that warrants some real looking into. That’s some real food for thought.
Also, that CSS layout module looks really neat.
Perfect! We just covered this in class today, and this is going to really help me finish my assignment. I appreciate it, Chris! Big fan here.
Yeah, I’m going to go wit cyborg_572 on this one.
or you could try frame work like blueprint or
960
Hmm… perhaps I live in a different CSS world, but my classic resolution of floated items not clearing is by using clear:both;
IE: this is floated!clear both creates the separation you were likely expecting
woops.
This is floated!
clear both creates the separation you were likely expecting
I find myself using Floats when I need to do just that…have some kind of content that behaved like a cloud, just sitting there and letting things happen around it. It makes sense to not have a height element (unless otherwise specified) since you are telling that section that it is, essentially, formless, allowing things to happen around it.
I find using a mixture of absolute/relative positioning and using floats to fill out the edges to be my own personal “correct” way of doing things, rather than a layout based on pure floats or pure positioning. Neither can really be correct yet, as CSS is still finding it’s place in the design/layout world of websites. I do think in it’s current state, embracing a holistic view of the code is the best bet.
That said, it would be nice to be able to create columns and sidebars without needing to specify something as ambiguous as a “float” or excessive as entirely positioning elemnts. Enter: CSS3. The more I dabble in it, the more I am on edge for the majority of users to upgrade their browsers, since it addresses many of the layout issues haunting CSS.
I guess what I am saying, is that there’s obviously nothing “broken” with CSS. As per this article, when you really look at it, its working just the way it was intended to. Yet its just a new(er) technology in one of the fastest moving industries and most of these so-called problems will be solved with the advent and (most importantly) support of newer attributes that help us progress to a world of purely semantic code. :)
I can’t remember where I read it now (possibly a sitepoint book) but someone was suggesting the table layout css properties to overcome the issue of using floats for complex layouts.
You get the structure and behaviour of a table – which admit it, is sometimes nice for layout – but without the crappy markup of an actualy table.
As for using overflow for clearing a float, for me it’s a big no-no. Just last week I had to re-do the float clearing on a couple of just-started templates because overflow was used, but it completely broke when I started to add the rest of the elements to the page.
:after rules, although some sort of contain rule would be nice.
Yeah, really a great Idea
I always wondered this and now I have the answer. Thanks for the info and i will certainly keep this guide in mind for next time i am working in css!
I stretch my non-floated containers with applying a <div class=”clear”></div> before the closing tag where .clear { clear: both; }.
Why would one use floats for positioning I can’t grasp. Floats are for elements to be floated. If you don’t want your next element to be part of the “flow” – clear it.
Ive always used float to position divs inside fixed divs, and normally always use overflow:hidden height:auto. I know you mentioned that fact that if you wanted to have an image sticking out of the side of div then it would be “hidden” but thankfully i have needed to do this and i can’t imagine its a very common problem people have if they lay out their sites correctly.
I always put clear:both on the next fixed div also to make sure it drops below. My sites look the same on every browser and have never had a problem using these.
i think floats are perfectly acceptable for layouts.
Overflow: hidden – Big mistake.
@Damian Smith: You’re site could be looking the same using a number of different techniques. One involves tables. One floats. There are other ways. Floats are there to help you in a special situation. You are using them as a standard, and trying to impose on them non-standard behaviour just to serve your pourpose. Maybe you should learn how to better CSS-style then how to better CSS-hack.
Thanks for the back to basics I have used overflow:hidden and always wondered if there was an alternative to having the parent respond well on floats and I guess this article has given me an extra hand on dealing with the mess in my layouts.
I do love your argument it work for me
great post and explanation
For your ‘average’ page, would a solution be the following CSS…
div { overflow:auto; }
And then over-riding that where necessary with more specific selectors. This’d certainly get rid of the need for lots of
<div class='clear'></div>
.What would be the pros and cons of that?
@Richard:
I think not. Depending on how careful you are (not) with you’re layout, unwanted scrollbars may appear out of the blue at a point or another in UX.
On the other side, overflow: hidden it’s also not a good solution, requering additional future hacks.
Remember, you’re chasing tricks not hacks :)
On a number of occassions I’ve used overflow:auto and had scrollbars show up randomly in IE6 or they show up in safari but nothing else or only in Opera and Firefox but not safari or IE6/7.
That’s why I stick with overflow hidden. The main problem with _firefox_ is that often something having to do with overflow hidden makes it not print the first printed-page of a web page when you try to print. No other browser has this problem in my experience.
And another thing, that it very clear to me:
if you need clear it means you don't need a float
For main layout that is.
You can force a container to clear in IE7 & IE6 like this. These are hacks and should be used sparingly. Best suggestion is to create an ie conditional stylesheet. So with the combination of :after and these, I don’t know if there is a need to but any clearfix’s in your markup.
*:first-child html .container{min-height:1px; /* IE7 */}
* html .container{ height:1%; /*IE6*/}
The clearfix is very useful when you need a quick solution. Saved me a lot of debugging.
Try this one:
.clearfix {
height:1%;
min-height:0;
overflow:hidden;
}
I used this method and so far away work great…
Why use two paragraphs?
Why not use one paragraph and a line-break?
“In order for that to happen, that upper paragraph needs to “collapse” as it were, and let the floated image stick out of the bottom of it.”
Um… I don’t see any good reason why the img tag has to be inside of the paragraph. It would work just as well if the img tag was between the 2 paragraphs (or preceded both which is how I usually do it) whether floats collapsed or not.
Plus wouldn’t photos in the body of an article tend to be asides or figures moving forward. Even more reason for them to not be within the P tag
Because images are inline elements and inline elements are perfectly valid things to put inside of block level elements.
“but what about if you wanted to hide horizontal overflow?”
overflow-x: hidden;
overfloy-y: contain;
Nevermind teoretical differences, I want to kindly thank mr. Chris Coiyer.
He is generous enough to pay/work for us to express ANY opinion, and host it EVEN if we atack his point of view.
Thank you.
display:inline-block is logical successor of float:left/right, though there are still some problems with it (whitespace between elements in formatted code).