CodeinWP CodeinWP

Clearing Floats: Why is it Necessary Even in “Modern” Browsers?

The other day, someone asked me the following question:

If I understand it right clear float is automatic in most modern browsers right?

If you’re new to CSS, then it would seem that the answer to this question should be “yes, of course — modern browsers don’t have these types of bugs!” But the necessity to clear floats is not a browser bug; it’s actually, well, more of a CSS feature. And it’s still needed in so-called “modern” browsers (assuming you’re using floats for layout).

This doesn’t mean, though, that clearing floats will always be necessary. The eventual goal of CSS layouts is to never need to use floats for layout. Instead, we want to be able to use a better method.

But clearing floats are a fact of developer lives today, and so I thought I’d explain why clearing them is still necessary, even in “modern” browsers.

What Does a Float Do?

Here is, in part, how the W3C spec explains what floats do:

Content flows down the right side of a left-floated box and down the left side of a right-floated box … 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.

You can see this behaviour demonstrated in the JS Bin below:

http://jsbin.com/azuwul/1/edit

Notice that the green box is acting as if the red box is not even there, rather than “flowing” around it like the text does. This is what floats do: They cause other floated elements and inline content to flow around the float, but other block boxes ignore the float.

The only problem I have with the W3C definition is that it sounds like it’s talking about absolutely positioned elements. So it seems that floats should have a different wording ascribed to them. I prefer to say that floats are taken out of the normal flow in relation to sibling block elements.

Regardless of the explanation, you should be able to see that no matter how far browsers advance, they will never clear floats automatically (as the original question seemed to assume) — because the behaviour of floats is not a bug; it’s a feature.

As Scott points out in the comments, it looks like there will indeed be an easy way to clear floats, using the contain-floats value for the min-height property. Interesting stuff. I believe this specification is only a month or two old, so I don’t expect browsers to have support for this any time soon. But good to know.

Float Clearing Methods

To round this post out, let’s cover the most popular methods for clearing floats.

clear: both/left/right
The primary way to prevent an element from flowing alongside a floated sibling is to use the clear property. Any value other than “none” will clear the element that you want to follow the float (rather than bump up against it).

overflow: hidden/auto
The main problem with floats is what you might refer to as the collapsing container, which causes background elements to disappear. In this case, you don’t have a trailing element that you can “clear” to fix this. But instead, you want the parent element to fully contain all the floated children. In this case, at the very least you’ll need to use the overflow property. Using a value of “hidden” or “auto”, the parent will expand to contain all floated children. Although this is probably the easiest way to clear floats, it’s really not recommended, because of the problem of scrollbars appearing or child elements being cut off due to positioning, margins, or CSS3 transforms.

I think the only time I would consider using this one is for a small widget-like box in the page that has floated children (like a tab switcher or something like that), where I know that positioned elements and margins are not going to be a problem.

clearfix
The best method to use to clear floats is the clearfix method. I can’t remember who originally came up with this, but the most updated and optimized syntax that works in all browsers is the one proposed by Nicolas Gallagher and used in HTML5 Boilerplate. Here’s the code:

.clearfix:before,
.clearfix:after {
    content: " ";
    display: table;
}
.clearfix:after {
    clear: both;
}
/* For IE 6/7 only */
.clearfix {
    *zoom: 1;
}

With that in your CSS, all you have to do is add a class of “clearfix” to any element that is “collapsed” due to floated child elements. Again, you could use the overflow method instead, but it’s not universally ideal. I’ve found it causes too many problems in complex layouts.

To Sum Up

Yes, float clearing is still necessary in modern browsers, and the best method is the clearfix method. But eventually, we want all in-use browsers to support an alternative, more intuitive method for doing CSS layouts, so we don’t have to worry about hacks and workarounds to fix these types of problems.

Post excerpt photo credit: Root beer float from Bigstock

26 Responses

  1. Coder says:

    I prefer to use clearing divs, they are harmless empty divs placed after any floated elements that don’t behave. They are not needed everywhere. I guess it’s just what you like, but we often use wrapper divs for similar purposes, so a clearing div is no different to a wrapper – that is, harmless structural support that works everywhere to address float issues. I avoid all CSS selector hacks and my sites work fine everywhere and I know they will work everywhere in future too. Sorry, but I just don’t subscribe to the clearfix method, and I don’t subscribe to tricking browsers into one thing in order to influence another specific browser such as IE6. I’d rather write logical code that works everywhere. No party tricks.

  2. Scott says:

    What a coincidence! I just saw this on Twitter: http://dev.w3.org/csswg/css-sizing/#the-contain-floats-value
    That basically solves the clearing problem, as long as you have a parent wrapper. A nice note for the future.

    Also FYI your JS Bin embedding is causing problems. On mobile Safari it keeps expanding downwards, getting taller and taller! Makes it near impossible to read the content below. There is a minor issue on desktop as well – it focuses the cursor inside the JS Bin, meaning the page jumps halfway down when you load it.

    • Wow, I don’t think I’d seen that contain-floats property before, thanks!

      And yes, I noticed the page jump, but that weird auto-height bug… I just noticed that before I read your comment. Thanks for the heads up, I’ve changed it to just a link. I’ll have to see if that’s a known bug and report it.

  3. Joe says:

    I’ve been developing for 12yrs now and have never had to use a clear method. Nor had any need to create IE specific CSS. I simply combine the float and display to always give me the desired look w cross-browser accuracy, even in IE6/7/8.

    • WhyYouNoShare? says:

      Please elaborate… what are some URLs of sites designed like this? Any code snippets? Your design is so good all versions of IE work seamlessly?

      You just seem like some CSS god bragging to us… share the love/examples!!!

      • You can do exactly what he’s saying, but unfortunately, in almost all cases, the result will be a layout that is fixed (i.e. non-responsive/non-fluid) and is more difficult to maintain or make changes to.

        For example, you can clear floats by just floating the container, too. But then you have to declare an explicit width on the container, and you have to ensure other elements around it are not affected negatively, requiring “clear: left” and whatnot. So it is possible, but it’s extremely impractical for fluid, easy to maintain layouts.

        • Joe says:

          Louis, I politely disagree. Wouldn’t impractical be to use hacks as opposed to simply using a single CSS file with all the required styling and nothing more? Even with % columns I’ve always been able use them effectively and efficiently w/o clearing them. Just gotta find the right mix of elements, float, display, and the like.

          • Well, if you can do it, then all the power to you. But you’re claiming to not need a float clearing method, which I don’t think is possible.

            I think you’d have to show an example layout to prove what you’re trying to say, because float clearing is absolutely necessary in certain circumstances. You either have to employ “overflow: hidden” or else add an extra empty element with “clear: both” or use a clearfix.

            Again, as the original response said, it would be good to see some example websites or just a layout on JSBin.com showing how you would do this.

        • Joe says:

          My solution since IE6 is simply in the overflow: hidden (and sometimes a combination of other styling – if needed depending on the situation/layout, etc… I’ve never run into a problem with this as of yet. Not in combination with positioning, margins, nor transitions. I’ve been doing element resets in conjunction with this since I can remember for Netscape and IE back in the olden days, lol.

          You simply apply other CSS accordingly with all other mark-up. I’ve always been able to find the right mix of pure CSS with this mix and never had to add extra tags or classes to code to clear a float.

      • Joe says:

        No, not bragging at all. I’m just always trying to find ways to reduce additional file loading usage of support scripts, css, etc..the more pure the solution, the better the long-term results. Everyone has their own methods that work better for them and their respective clients. All good.

  4. Fabio Venni says:

    I usually float the containers (the parent basically) and apply the clear: both rule to IDs (or HTML5 tags when content is simple) rather than to classes. In a complex layout you won’t have more than 3/4 selectors per page, and if you are clever (and your CMS allows it) 5-10 times side-wide. And its cross-browser. However I think is a CSS2.something hack and is not allowed by CSS3 (will check).

    • helphope says:

      I’ll go with he clearfix method. But apart from the float layout method, (and apart form the better method which is yet to come) what else there remains in modern trend?

  5. Radu says:

    Very good article that sums up all recent information regarding clearing floats.

  6. Mot gio says:

    To clear affect of float with it’s parent, I often use overflow or float it’s parent.
    I use clear fix when I can control my html file :)

  7. Ashokkumar says:

    well, it clears my misconceptions about float.

  8. Mars says:

    Whats wrong with just using and in your css .clearfix {clear:both;
    }

  9. Bill says:

    I do web design and believe that the world is not yet ready for HTML5. What has this statement have to do with this article? Everything, let me explain. The first link posted to explain floats visually was http://jsbin.com/azuwul/1/edit and herein lies the reason. When I first started exploring and reading about HTML5 I was elated on the new features. But as I researched further I started discovering the limitations and the different phases and processes that were taking place, a work in process as it is. I then started researching the market share of browsers in use. IE 7 still has a strong foothold and is HTML5 illiterate, not good. So this link http://jsbin.com/azuwul/1/edit provides a great example to this paradox. Open it with IE7 then compare to Chrome, Firefox or others. I use IE7 for one reason and one reason only, my clients are paying me to provide services and content to all potential visitors, not just the tech oriented or people with newer systems! Are my sites boring, static, and cookie cutter based – maybe, but they are not directed to a spinning canister versus a great visual explanation of floats. By the way, including “Your browser does not support…” should be a catch phrase to those of you who work with HTML5 and to help nudge visitors to update their browser. Do I ignore the potential of HTML5? No, I still build sample pages, read, follow its development… oops, out of lines for my rant;)

    • JS Bin pages won’t work in IE7, so that might be part of the reason. JS Bin is for techies, so no reason to spend dev time on that. But if you have clients that require IE7, you could encourage them to install Chrome Frame.

      • Bill says:

        It is not so much the client as it is their customer base. The one argument that I do like in the HTML5 community is to simply place the “Your browser doesn’t support… …please upgrade to Chrome, FireFox”, what have you. If enough of the web designers would implement this then it might force the visitor to think they are missing out on something new and exciting instead of thinking they have just landed on the worst site on the web. I realize there are many partial work-a-rounds and hacks, but time is money, so for right now I’ll just lay low and be forced to play catch up when they have the final styles approved.

  10. Naveed says:

    This article really solved my ambiguity regarding floats.. Thanks for sharing!

  11. Geeksripe says:

    Thats really helpful , thanks for sharing such great info with all of us

  12. Alan Gresley says:

    Clearing floats by using the overflow values of auto or hidden only took off because this is what was supported by all browsers around late 2007 and early 2008. At the time, Firefox had not implemented inline-block. The reason why overflow values of auto or hidden contain float is because they establish [a] new block formatting contexts for their contents. More precisely, the spec (http://www.w3.org/TR/CSS2/visuren.html#block-formatting) says:

    “Floats, absolutely positioned elements, block containers (such as inline-blocks, table-cells, and
    table-captions) that are not block boxes, and block boxes with ‘overflow’ other than ‘visible’
    (except when that value has been propagated to the viewport) establish new block formatting
    contexts for their contents.”

    You don’t use absolutely positioned elements since they are removed from the flow completely. Float themselves are first laid out according to the normal flow, then taken out of the flow as suggested here.

    http://www.w3.org/TR/CSS2/visuren.html#positioning-scheme

  13. Abital Deng says:

    Great article but i still hate floats, they always seem to mess up everything no matter what you do.

  14. Martijn says:

    The best method to clear a float is NOT a cleafix. It’s intrusive in the html, and lacks any sematics. The best way is whatever works. There is no golden hammer to clearing your floats. Neither method is the best or the worst.

    However, creating a class to clear a float is bad practise. You should always avoid creating classes that specifically instruct certain CSS behaviour without it describing why. Make a clearfix on the elements you need, just on the “news-block” class or whatever you might have.

    That said, avoid thinking modern as well. Avoid avoiding floats an favour of display:inline-block or flexbox, as they will introduce other problems that may not yet have been solved. Floats are your friends, and my best friends are overflow and clear.

    • Unfortunately, it’s not that simple. I used overflow:hidden or overflow:auto for many months and then realized it was not a good method. I eventually had problems with content being cut off and other issues. If you overuse overflow:hidden/auto, you will have problems. The clearfix does not affect document semantics. Classes have no effect on semantics. That’s why it’s the best method to use.

Leave a Reply

Comment Rules: Please use a real name or alias. Keywords are not allowed in the "name" field and deep URLs are not allowed in the "Website" field. If you use keywords or deep URLs, your comment or URL will be removed. No foul language, please. Thank you for cooperating.

Markdown in use! Use `backticks` for inline code snippets and triple backticks at start and end for code blocks. You can also indent a code block four spaces. And no need to escape HTML, just type it correctly but make sure it's inside code delimeters (backticks or triple backticks).