All About Floats

* 6/30/2008  —  80 Comments *

by: Chris Coyier

What is “Float”?

Float is a CSS positioning property. If you are familiar with print design, you can think of it like an image in a layout where the text wraps around it as necessary.

In web design, an image that is floated remains a part of the flow of a web page. That means that if it changes in size or if the elements around it change, the page will automatically adjust (reflow). This differs from page elements that are absolutely positioned. Absolutely positioned page elements are removed from the flow of a web page. Absolutely positioned page elements will not affect any other page elements, whether they touch each other or not.

 

What are floats used for?

Besides simple examples like floating an image within a block of text, floats can be used to create entire web layouts.

Floats are also helpful for layout in smaller instances. Take for example this little area of a web page:

These types of layouts can be handled using absolute positioning inside of relative positioning as well, but floats are a more flexible. Let’s say the size of that avatar image were to change. With floats, the box could re-flow to accommodate the bigger size, whereas an absolutely positioned layout would create problems:

 

Problems with Floats

Oh, where to begin. Floats are fragile. They are full of issues and cross-browser quirks. Perhaps most significant is the need to clear floats in some situations. There are a couple reasons floats need to be cleared. First I’ll show you some examples of why a float would need to be cleared, then we’ll cover how to go about clearing.

Clear the float to fix the height of the parent element.

Elements which contain floated elements do not calculate their height as you might expect. In fact, if the parent element contains only floated elements, browsers will render the height at zero.

If you clear the float before the closing tag of the parent element, you can fix this.

 

Clear the float to start a new row.

Lets say you have a grid of floated objects.

Then let’s say you want to create a break in that grid in order to start a new row. Because, you know, it just makes sense visually for whatever reason.

 

Clearing only the left or right.

The above two needs for clearing call for generic clearing, that is, clearing both the left and the right of the float. Because floats can be floated left or right, you can also clear either the left or right only. This can be useful when clearing both sides would be problematic to your layout.

If both sides were cleared in the above example, the second image would have been pushed down to where the text block ended.

 

Different techniques for clearing floats

As with everything in CSS, there are more ways than one to do this.

Applying clear exactly where you need it.

The clear CSS property does exactly what it says on the box. The problem lies in where and how to apply an element to the page with the correct clear property.

  • Apply clear: both; to the element directly after where you need the float cleared. Take the example near the top of a web page layout with a full-width header and footer and main content floated to the left with a sidebar floated to the right. In order to get that footer to show up in the right place, you MUST clear the float before it. In this simple example, you could simply apply clear: both; to the footer div itself.

     

    This technique is wonderful because it works and it adds no superfluous markup to your code. However, it breaks down in more dynamic sites sometimes. What if, for example, you ended up having to add a new page element above the footer but below the main content? You would need to remember to apply the clearing to this new element now instead of the footer. It is often easier to think in terms of where you need to clear the float instead of on which element you need to clear the float (and is easier to implement).

  • Clear the float with an empty page element. <div>’s do nicely because generally you don’t have any styling applied to generic div’s (like you might a <p> element) and they don’t have any other special page functionality (like a <br />). Where ever you want to clear the float just add a div like this: <div style=”clear: both;”></div>. I find looking at inline-styling unappealing so I choose to make a class for this style and apply a “clear” class to that div instead, but that is just a personal aesthetic choice.

The empty div method HTML:

    ...part of floated element
</div>

<div class="clear"></div>

<p> ... ahhhh, now I'm clear </p>

CSS:

div.clear { clear: both; }

Overflow: auto; on the parent element

I can’t explain to you why (wish I could), but applying the CSS property overflow: auto; to the parent element will cause the height to be calculated properly. It will grow to enclose all the floated elements instead of collapsing. This can be very useful and it’s very clean, but it has some issues of course. The major one being there often isn’t a parent element it makes sense to use it on. Think of times where you would need to clear the float more than once within the same single parent, this isn’t going to help you there.

Another problem is that you may want or need to use that overflow property for other purposes. What if you want to hide the overflow on that particular div? You can’t. You’ll have to wrap the div in yet another div to accomplish that.

The clearfix hack (clearing with the :after pseduo-class)

Although aging, the positioniseverything article on using a pseduo-class to clear the float is still very functional. And pretty brilliant, if you ask me. To explain simply, it adds a bit of content after the element. This bit of content (a period or space, usually) does the clearing the float, but is hidden from view.

Here is the code, applied via a class to any element you need to do the clearing:

/* This needs to be first because FF3 is now supporting this */
.clearfix {display: inline-block;}

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

/* Hides from IE-mac \*/
* html .clearfix {height: 1%;}
.clearfix {display: block;}
/* End hide from IE-mac */

The article has a warning claiming that the technique is getting old and refers to the overflow: auto; fix. I don’t share their sentiment that this technique is outdated. This is fundamentally different than the overflow fix. With the clearfix, you apply the clearing class to the element itself, not a parent element. This means you can still use it even where there isn’t a parent element that makes sense and apply it by thinking abut where the float needs to be cleared.

Updates: Thanks to John for pointing out that FF3 now supports inline-block, so that statement will need to go first in the CSS so it can get over-written by the :after pseudo-class. Thanks to Brent for pointing out the Perishable Press article suggesting using a space instead of a period and adding font-size: 0;.

 

Another float problem: Pushdown

I feel like this deserves special attention because of how often I am helping someone troubleshoot a problem they are having with “pushdown”. Again looking back at the example at the top of this article with the Main Content area floated left and the Sidebar floated right. This is a common structure for many blogs.

Whether it’s fixed or fluid, both of these areas will have a set width. They way floats are supposed to behave, if an element within the main content area exceeds the width the the main content area (say, you inserted an image that was too large) it will simply extend beyond and overlap anything it needs to. The way IE 6 handles this, is much different. If an element within the main content area exceeds the bounds in IE 6, it will simply push the sidebar down below, completely borking your layout.

The solution? The best solutions is just not put anything inside the main content area that will spill over. For better protection, and it if it works with your layout otherwise (no set heights!), you could set the overflow to hidden to hide any spillover. Yet another solution would be to use absolute positioning to get the sidebar over on the right. Remember though, absolute positioning removes the element from the flow of the page — just something to be aware of.

A List Apart just recently had an article on how to use “faux” absolute positioning, which an interesting read and covers a new technique for layout that has a lot of the advantages of absolute positioning while retaining flow and fighting the frailty of floats.

 

Quirks about floats

Another thing to remember when dealing with IE 6 is that if you apply a margin in the same direction as the float, it will double the margin.

IE 7 has a little quirk of it’s own not respecting bottom margin on children inside floated objects.

Responses

  1. Sebastian says:

    thanks! Always been wondering about that!

  2. John S says:

    One note about .clearfix
    Firefox 3 now recognises “inline-block” which will over write the “.clearfix:after” and not clear properly.
    To get FF3 to clear properly, move the “inline-bloc”k statement above the .clearfix:after in your stylesheet or just remove it (IE/MAC fix) depending on your sites metrics.

  3. Chris Coyier says:

    @John: Very good point, I will update that in the article.

  4. V1 says:

    http://www.quirksmode.org/css/clearing.html

    That is what i use for clearning my floats. hotness.

  5. Great job on this! You should explain things in this style more often, it’s really refreshing and easy to follow! :)

  6. Epic Alex says:

    Hi Chris, just a question about where you say:

    In fact, if the parent element contains only floated elements, browsers will render the height at zero. – If you clear the float before the closing tag of the parent element, you can fix this.

    I’ve always resolved that by floating the parent element as well, is this bad practice, even though it achieves the same thing? Plus that doesn’t add non-semantic markup.

    Just wondered what your thoughts were?

  7. Chris Coyier says:

    @Epic Alex: But what if you don’t want the parent element floated? That could cause layout problems of it’s own. If you use the clearfix method or the overflow: auto; method, you can also clear the float fixing the parent element size without adding extra markup.

  8. Mat says:

    This is my “Ah-Ha!” moment… haha.

  9. liam says:

    Wow, this is sweet. I think the way you’ve presented the information is great, definitely would love to see more set out like this. Nice read.

  10. Brent Traut says:

    Chris,

    I discovered a very relevant link in the last few days concerning clearfix. I suggest you check it out and possibly even apply its recommendations to this article:

    http://perishablepress.com/press/2008/02/05/lessons-learned-concerning-the-clearfix-css-hack/

    Brent

  11. Tim Wright says:

    I think that’s the most comprehensive explanation of floats I’ve ever seen, very nice

  12. Marco says:

    Now that’s what I would really love to call one great article, explaining everything even ’till the minor details.

    Keep up the great work.

  13. pepelsbey says:

    Some important, but missed info about clearing:

    — FF, Safari, Opera, IE7 (!) #parent { overflow:hidden }
    — For IE5.5–6 #parent { zoom:1 }

    Imho, it’s the easiest way to clear floats.

  14. Matt says:

    I can’t believe all these years I had a completely different perception of how “clear” worked and could never figure out why it worked sometimes but not others. It’s all perfectly clear (bad pun) now. Thank you so much for this article.

  15. Jason says:

    Unfortunately, I learned this the hard way years ago! Good article, thanks!

  16. Anders says:

    Nice summary Chris!

    Would love to see more of these in the future..

    Elements which contain floated elements do not calculate their height properly. In fact, if the parent element contains only floated elements, browsers will render the height at zero.

    This is actually the correct behaviour according to the specs, so it’s not a matter of the browser getting it wrong. Here’s an article illustrating why this makes sense.

  17. Brandon says:

    Instead of adding more divs to my markup, I simply use <br />inside of my parent div, then use

    .parent br { clear: both; }

    in my css to make the parent div clear and expand to the height of the internal floats. It has the same effect with less markup and div confusion.

  18. Gary says:

    Good article. Floats are great, but they can be aggravating at times.

    The article on faux absolute positioning you mention is, as you said, interesting. I played with it and really liked it. At least until I read this argument against faux absolute positioning.

  19. Chris Coyier says:

    @Brent: Thanks, I’ll add that info to the article.

    @pepelsbey: if you use overflow: hidden, you shouldn’t even need that zoom: 1 for IE 5.5 and 6, as that will trigger the hasLayout attribute as well.

    @Anders: Nice link! And this is good information. I shouldn’t have implied that browser is doing something wrong by collapsing the parent. Most of the time when it’s happening though, it feels strange and illogical even though it’s behaving correctly.

    @Brandon: <br />’s are OK to use as well, but as I mentioned in the article I prefer a div as it doesn’t have any particular special function (like a br does).

  20. Phillip says:

    Awesome awesome awesome post. I think if there is one thing I use the most it’s “float”. I actually didn’t know about some of these bugs. Thanks!

  21. jbj says:

    An excellent article, really. I enjoyed reading it.
    Greetings from Belgium!

  22. Jeff Starr says:

    Thanks for the ping Chris — I updated my Clearfix article to reflect the Firefox-3 fix presented in your post. Now I’m off to update a gazillion different stylesheets!

    Btw, I am fairly certain that the “official” abbreviation for Firefox is “Fx” and not “FF”, for whatever it’s worth..

  23. Just when I thought I knew a lot about floats…. thanks Chris!

  24. guest says:

    Something OT:
    Basicly I don’t think the “float” property is tend to be used as a layout property,
    but as a typography property maybe — it’s coming from the “align” property of a IMG tag.

    There is no such a property specificly tend to be used for layout yet in css2.1 , you say “position”? well, position is just so lack of control.

    CSS2.1 is still basicly a document decorating language, same as CSS1, complex layout is far out of it’s range. Every CSS technic now we are using for layout, is a kind of hack, including float and position. What about table layout? Yes it’s obviously a hack, too.

    So, we are hacking everything here.

  25. Fouad Masoud says:

    Blockquote Overflow: auto; on the parent element

    overflow: hidden; works exactly the same as overflow: auto; it clears the float and if you specify a width it makes sure that the parent element hides any thing that goes out the original width. With width specified you can fix a couple of IE6/7 bugs where margin bottom of the last element doesn’t work.

    Generally speaking and i think everybody here knows this. specifying a width to elements solves like 70% of IE rendering bugs.

    @Jeff Starr it is Fx they used it on they site for a while, i cant find it there anymore though.

    this is a link to whats new with Fx support to CSS http://tinyurl.com/yuxlbs

  26. Useful article to have saved, picked up some good tips too!

  27. Olivier J says:

    I don’t want to sound rude but your article did sound a little bit confusing to me, not “clear” enough I would say:)

    Here is a previous article I had read which explains the same points in a much simple and complete way.

    http://kilianvalkhof.com/2008/css-xhtml/understanding-css-positioning-part-1/
    http://kilianvalkhof.com/2008/css-xhtml/understanding-css-positioning-part-2/

  28. Travis says:

    I think this is a very detail coverage on float usage! I believe you can never have enough wrappers to make sure no surprises from your floating elements.

  29. Sean says:

    Thank you for a well written article. It really helped clear up some of the confusion I had re: floating.

  30. Simon says:

    Thanks mate – very helpful. Great looking site too!

  31. Suzy says:

    thanks, really nice article

    just a couple of things that have come up in the comments more than the article itself…

    if you use overflow: hidden, you
    shouldn’t even need that zoom: 1 for
    IE 5.5 and 6, as that will trigger the
    hasLayout attribute as well.

    The overflow property only triggers hasLayout=true in IE7, so afaik 5.x and 6 will still need something else like zoom to keep up.

    The the clearfix hack is actually doing both you could lose the height 1% part if you no longer need to support IE5, IE5.x and upwards is getting hasLayout from the combination of inline-block and display: block (needs to be in two separate rules still though)

    if you’ve no need to support IE5 (Mac or Windows) the hack will work with just this now:

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

    I’m a little confused with the FF3 advice though, it should not be necessary to reorder the rules. though it will do harm, the :after rule is targeting a different thing than the .clearfix rule itself so the display property of one will not overrule the other

    the bit inside the commented backslash hack (hide from mac) is read by all browsers except IE/Mac so FF3 will still see the {display: block} part too, the same as Opera and IE, Safari all those who already supported inline-block really .. anyway that is the part that is resetting the display:inline-block back to block for all browsers on the clearfix’ed’ element itself which in my test includes FF3.. in IE the combination of the two rules is also setting hasLayout while at the same time maintaining the display.. you could simply replace the two rules with zoom:1 or width: 100% too for the same effect.. inline-block was only necessary for Mac though it has the side effect that it also works for Win now too if width is not known and you don’t want to use zoom

  32. Jeff Starr says:

    …it should not be necessary to reorder the rules. though it will do harm, the :after rule is targeting a different thing than the .clearfix rule…

    I think you mean “though it will do no harm,” which seems correct because .clearfix and .clearfix:after are indeed targeting two different aspects of the (X)HTML document. Reordering the rules as suggested in the article shouldn’t change the functionality of the clearfix hack. Firefox-3’s support of inline-block is effectively of no consequence to the clearfix hack, regardless of how the first two selectors are ordered within the stylesheet.

  33. Suzy says:

    yes, I meant do NO harm.. thanks

  34. Visar says:

    Hello there

    Can I find on the fly the height of a div, if it is filled with some text dynamically?

    The thing is that I can not push down the footer without using the “top:” attribute, so
    my content is sometimes small and sometimes big, if I can know how much is the height of the
    div content than using javascript I can set the footer to have a top attribute of the height of the div content, and everything is fine and good.

    Ciao and thank you for the great article.
    If you can help me please help me.

    I have tried everything and I cannot do more, I thought may be you can help me

  35. Chris Coyier says:

    @Visar: There are ways to do this, but I really recommend against using javascript for page layout. That is bad mojo. If you need to keep your footer on the bottom of the page google “Sticky Footer” and use that technique. It’s very slick and pure CSS.

  36. That’s definitely the best article about floats I’ve ever seen – thanks!

    I love the design of this site. In fact I’ll go so far as to say it’s one of the nicest designs I’ve ever seen.

    What is the handwriting-esque font in the images used to illustrate this article?

  37. Bernhard says:

    You say: “In web design, an image that is floated remains a part of the flow of a web page.”

    The CSS 2.01 spec 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 didn’t exist.”

    So who is right? You or W3C?

  38. Chris Coyier says:

    @Bernhard: Perhaps I was using the word flow incorrectly? I don’t know… All I know is floated page elements will still push other boxes around when they change size. They can affect other page elements and other page elements can affect them, which seems to me like they are part of “flow” unlike absolutely positioned elements.

  39. Paul B. says:

    I can’t think of a single thing that’s caused me more woes than floats. When they work, they work, but getting to that point is full of all kinds of trickery. This is a great guide that I’ll definitely bookmark for the next time I need to solve a float problem.

  40. Christian says:

    Nice float post!, really helped me :)

  41. Thanks, great post – very easy to follow. I especially love hack tips and problem solutions You looked after.

  42. danny says:

    you’ve done great job explaining this, it took me aaaaaaaaaaaaaaaaaages to figure all this stuff out when i started using css layouts, and even now you’ve shown me a few things i never understood. where were you when i needed you, all the pain you could have saved me!

  43. Josh says:

    Great article…answered all my questions.
    Thanks and keep up the good work.

  44. Walkman69 says:

    This is a really great article. Actually it’s the best information i have stepped over since the time i learnt about how to use Favlets and when i came in contact with
    http://browsershots.org/.. Look into thoose fenomena if you don’t already know about’em =)..
    They are almost as great as your page.. ^^

  45. Marilyn says:

    Thank you for this post… you’ve helped me stop pulling out my hair!!

  46. Nocom says:

    Thanks for post and download section

  47. ballu says:

    Excellent articles… My 90% problems are solved !! gr8 :)

  48. Combus says:

    That was really usefull! I also watched the video :P

  49. Pete White says:

    Great article, its amazing all the little quirks between browsers. I’ve spent a lot of time fixing little CSS issues!

  50. k says:

    really usefull. bookmarked :)