CSS-Tricks PSD to HTML

All About Floats

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.


Theoretically Related Articles:


Responses


  1. 1

    Gravatar

    thanks! Always been wondering about that!


    Comment by Sebastian — June 30, 2008 @ 6:04 am

  2. 2

    Gravatar

    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.


    Comment by John S — June 30, 2008 @ 6:20 am

  3. 3

    Gravatar

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


    Comment by Chris Coyier — June 30, 2008 @ 7:10 am

  4. 4

    Gravatar

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

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


    Comment by V1 — June 30, 2008 @ 7:17 am

  5. 5

    Gravatar

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


    Comment by Thomas Offinga — June 30, 2008 @ 9:21 am

  6. 6

    Gravatar

    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?


    Comment by Epic Alex — June 30, 2008 @ 9:39 am

  7. 7

    Gravatar

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


    Comment by Chris Coyier — June 30, 2008 @ 9:54 am

  8. 8

    Gravatar

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


    Comment by Mat — June 30, 2008 @ 10:08 am

  9. 9

    Gravatar

    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.


    Comment by liam — June 30, 2008 @ 10:15 am

  10. 10

    Gravatar

    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


    Comment by Brent Traut — June 30, 2008 @ 10:39 am

  11. 11

    Gravatar

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


    Comment by Tim Wright — June 30, 2008 @ 10:43 am

  12. 12

    Gravatar

    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.


    Comment by Marco — June 30, 2008 @ 10:47 am

  13. 13

    Gravatar

    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.


    Comment by pepelsbey — June 30, 2008 @ 1:02 pm

  14. 14

    Gravatar

    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.


    Comment by Matt — June 30, 2008 @ 1:10 pm

  15. 15

    Gravatar

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


    Comment by Jason — June 30, 2008 @ 1:14 pm

  16. 16

    Gravatar

    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.


    Comment by Anders — June 30, 2008 @ 1:45 pm

  17. 17

    Gravatar

    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.


    Comment by Brandon — June 30, 2008 @ 1:54 pm

  18. 18

    Gravatar

    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.


    Comment by Gary — June 30, 2008 @ 2:11 pm

  19. 19

    Gravatar

    @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).


    Comment by Chris Coyier — June 30, 2008 @ 2:42 pm

  20. 20

    Gravatar

    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!


    Comment by Phillip — June 30, 2008 @ 2:42 pm

  21. 21

    Gravatar

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


    Comment by jbj — June 30, 2008 @ 3:03 pm

  22. 22

    Gravatar

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


    Comment by Jeff Starr — June 30, 2008 @ 3:36 pm

  23. 23

    Gravatar

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


    Comment by Eric Wendelin — June 30, 2008 @ 5:44 pm

  24. 24

    Gravatar

    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.


    Comment by guest — June 30, 2008 @ 7:01 pm

  25. 25

    Gravatar

    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


    Comment by Fouad Masoud — July 1, 2008 @ 12:10 am

  26. 26

    Gravatar

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


    Comment by Chris Spooner — July 1, 2008 @ 1:58 am

  27. 27

    Gravatar

    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/


    Comment by Olivier J — July 1, 2008 @ 5:41 am

  28. 28

    Gravatar

    @Fouad Masoud:

    http://www.mozilla.com/en-US/firefox/releases/1.5.html#FAQ

    Check #8..


    Comment by Jeff Starr — July 1, 2008 @ 8:00 am

  29. 29

    Gravatar

    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.


    Comment by Travis — July 1, 2008 @ 4:25 pm

  30. 30

    Gravatar

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


    Comment by Sean — July 1, 2008 @ 10:10 pm

  31. 31

    Gravatar

    Thanks mate - very helpful. Great looking site too!


    Comment by Simon — July 2, 2008 @ 7:55 pm

  32. 32

    Gravatar

    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


    Comment by Suzy — July 9, 2008 @ 1:02 am

  33. 33

    Gravatar

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


    Comment by Jeff Starr — July 9, 2008 @ 6:49 am

  34. 34

    Gravatar

    yes, I meant do NO harm.. thanks


    Comment by Suzy — July 9, 2008 @ 11:07 am

  35. 35

    Gravatar

    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


    Comment by Visar — July 11, 2008 @ 4:26 pm

  36. 36

    Gravatar

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


    Comment by Chris Coyier — July 11, 2008 @ 7:11 pm

  37. 37

    Gravatar

    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?


    Comment by Caesar Schinas — July 13, 2008 @ 11:01 am

  38. 38

    Gravatar

    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?


    Comment by Bernhard — July 18, 2008 @ 6:46 am

  39. 39

    Gravatar

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


    Comment by Chris Coyier — July 18, 2008 @ 8:42 am

  40. 40

    Gravatar

    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.


    Comment by Paul B. — August 3, 2008 @ 2:53 pm

  41. 41

    Gravatar

    Nice float post!, really helped me :)


    Comment by Christian — August 7, 2008 @ 5:48 pm


Leave a comment

Sick of typing in all this info everytime you comment? Register or Login and save yourself time!

Live Comment Preview


Thank you for visiting CSS-Tricks! I'm glad you found an article useful enough to print out! Remember to visit css-tricks.com often for more fresh content.