How to clear CSS floats without extra markup – different techniques explained

When using floats in CSS, without a doubt you have encountered the interesting effects it will have on the following content. Here I will show you different ways to clear floats without any extra mark-up.

The way to solve it is to use different methods applied to the element containing one or several floated elements. From my experience, there are three major approaches:

  • Floating the containing element as well.
  • Using overflow: hidden on the container.
  • Generating content using the :after CSS pseudo-class.

Floating the container

If you float an element containing floats, it will encompass its content. The side-effect of this is that we add another floated element to the page, while we most of the times want it to behave as a regular block element. That is solved by applying a width of 100% to the container as well, so it forces a line-break before the content after it.

Code

.container-with-float{
    float: left;
    width: 100%;
}

Downsides

  • Setting a width to 100% might collide with desired padding.
  • IE 6 seems to add an extra bottom margin in some cases.

Adding overflow: hidden to the container

If you add overflow: hidden to the containing element, it will automatically adjust its height and take the floated children into account.

Code

.container-with-overflow{
    overflow: hidden;
    /*
        Use height: 1%; or zoom: to trigger hasLayout in IE 6.
        My suggestion is to serve this only to IE 6 through a
        separate stylesheet included with conditional comments.
    */
    height: 1%;
}

Downsides

  • If you want a fluid height, there can be some situations where using overflow can collide with other wanted behavior. A suggestion is to play around with things such as overflow-x: hidden and/or overflow-y: hidden in those cases.
  • hasLayout has to be triggered for IE 6, using height: 1%; or zoom: 1;. My recommendation is to have this in a separate IE 6 stylesheet, included through conditional comments.

Generating content through CSS

Another alternative is to use the CSS pseudo-class :after to generate content after the containing element, using it to clear floats and then hiding itself. Personally, I don’t like this approach since it generates content to the page that has nothing to do there in the first place.

Code

.container-with-generated-content{
    /*
        This is necessary to trigger hasLayout, for both IE 6 and IE 7!
        My suggestion is to serve this only to IE through a
        separate stylesheet included with conditional comments.
    */
    height: 1%;
}

.container-with-generated-content:after{
    content: ".";
    display: block;
    height: 0;
    clear: both;
    visibility: hidden;
}

Downsides

  • Not IE 6 nor IE 7 supports the :after pseudo-class, so you need to apply a hasLayout fix for both of them. Note that IE 7 also supports a hasLayout fix.
  • It generates content that really hasn’t any semantic value.

A little test page

I’ve put together a little test page where you can see the three different ways to address this problem in action. Play around with it and let me know if you encounter any problems!

Do you use any other approach which works fine for you? Please let me know!

Posted in CSS,Developing,Technology,Web browsers |

83 Comments

  • I nearly always end up using option 1: and in fact end up floating most items on the page. See the Float nearly everything method

    In doing this, I rarely have any issues with IE6 (just the odd width issue and double margin float bug) and next to none with IE7. It has to be said that this technique works best with a fixed width design and sometimes it flails if you attempt a liquid/elastic layout.

  • [...] Nyman sums up the different techniques on clearing CSS floats without extra markup. Must say I’m still hooked to the <br style=clear:both /> way of clearing :$ Spread [...]

  • Richard Mulhern says:

    I've never seen the overflow: hidden technique before, but I am a fan of the overflow: auto method. Works most of the time in all browsers for me, and when it doesn't its usually because of something I'm doing.

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

  • Chris says:

    Thanks for summarizing these methods!

    Like Richard I often use overflow:auto;.

  • Andreas says:

    I always use the :after-method for proper browsers, height: 1% for IE6 and display: inline-block; for IE7.

    Works fint every time i think.

    Example

  • I use both generated content and hasLayout for IE, simply because I've never run into problems with them before (fixed, liquid, or elastic). However, it isn't as universal as <code>overflow</code> seems to be.

    I make one addittion to the generated content though and that is <code>font-size: 0</code> for Firefox 2. It seems to be required for it to take up absolutely no space at all — perhaps a bug, because I don't remember needing this for Firefox 1.5.

    My general hasLayout rule utilizes <code>zoom: 1 </code>, with the occassional need to fall back to <code>height: 1%</code> for IE5.x.

    All in all, definitely not as pretty, but in my experience incredibly robust. It has never failed on me once.

    As for your downside for the generated content technique that is adds no semantic value, I say it doesn't matter. It's a dot that's not in the actual markup. :-p

  • Sam says:

    Translated an article to Russian:

    http://rmc.net.ru/article/web/clear-floats/

    Sorry not to asking permission first.

    p.s. All copyrights are in place.

  • Bramus! says:

    Very nice overview Robert!

  • I'm with Richard and Chris on this…"overflow: auto;" all the way! However, I have recently encountered a bug in Firefox that causes elements with contain floats and have overflow: auto applied to them to be be able to get focus. This means that if you have a div element which contains a floated label and input element…when you try to tab to the next input element you will tab to the div wrapping that element first! It also displays the dotted line focus outline on that div which can completely throw off your layout.

  • Robert Nyman says:

    Thanks for your comments!

    Sam,

    That looks just fine! :-)

    Richard Mulhern,

    Good point, <code>overflow: auto</code> seems to work the same way, and it removes the possible downside of wanting it to have a dynamic height sometimes.

    Shane,

    Hmm, interesting. Does that apply to all <code>overflow</code> solutions, i.e. <code>overflow: hidden</code> as well?

  • Jeff L says:

    I use the <code>overflow: hidden</code> and <code>zoom:1</code> method.

    I use hidden for the overflow and not auto, and FF 1.7 had some bugs with using auto where it would show the scrollbars on certain items.

    And i use zoom not height to trigger hasLayout because it has no ill effects in any other browser and can be put into your main stylesheet without the need for any CSS hacks.

  • Joe says:

    Excellent article. Thanks you.

  • [...] How to clear CSS floats without extra markup – different techniques explained – Robert’s talk (tags: _css tips webdesign) [...]

  • DocZayus says:

    Thanks.

    I always love getting new CSS tips.

  • Robert Nyman says:

    Jeff,

    Good to hear. Unwanted/unexpected scrollbars were one of my fears, when I read about using <code>overflow: auto</code>.

    I'd rather have all invalid CSS/workarounds etc to make things work in IE in a completely separate file (included thorugh conditional comments), to make sure that the master CSS file/-s are intended for every web browser.

    Joe, DocZayus, Navdeep,

    I'm glad that you liked it!

  • [...] zuletzt heute Nachmittag – immer mal wieder Ärger mit der CSS-Eigenschaft float hat, sollte hier mal reinschauen. Anschaulich wird am Beispiel erklärt wie man das “float” ohne [...]

  • [...] various methods for clearing floats without creating additional markup. Robert Nyman posted a nice article showing several of the well established techniques. I was not satisfied with any of the techniques [...]

  • Good summary – it matches with my experience. I'm mostly using overflow hidden, but when using relative/absolute positioning within the containing div it cuts things off, so I switch to another method when I need to.

  • [...] How to clear CSS floats without extra markup – different techniques explained – Robert’s talk (tags: css float layout markup) [...]

  • NICCAI says:

    Lately I've been using:

    W3C: { display: table; width: 100%; }

    IE: { zoom: 1; }

  • Nice collection of tips Robert. Personally I stick to the float way which works for me but thanks for opening my eyes to other possible ways to skin the cat/ get the job done.

  • Kevin says:

    <code>

    .container-with-generated-content:after{

    content:"."; display:block;height:0;clear:both;visibility:hidden;_zoom:1

    }</code>

  • I usually use clearfix: http://www.positioniseverything.net/easyclearing….. It's method with :after and some browser fixes.

  • [...] Robet Nyman ger tips pÃ¥ hur man clear:ar float utan onödig [...]

  • Rafael says:

    I usually use {display:inline-block} for IE and {display:table} for other(better) browsers with {height:auto} for everyone and it worked fine (until now).

  • Kapitancho says:

    I prefer

    div.to_be_cleared {

    width:100%;

    overflow:hidden;

    }

    and that's all.

    In cases where a different width is needed, these 100% are simply replaced by the desired width value.

  • Seraphim says:

    Millions of thanks Rob for this god-send article!

    I've been floating elements with various widths for years (which is not good for fluid layouts) and I can't believe only now do I know about this overflow: hidden trick!

  • Bruno says:

    I have read some dozen or so recommendations for float clearing and not one of them is more practical or as clean as inserting a dummy "clearer" div element into the markup.

    Practical means clean, quick, easy, and above all, compatible for every browser. No hacks, no junking up your CSS, no need to double or triple-nest your content.

    All this would be a lot more straight forward if the clear property just worked in an ideal fashion when attached to any styled elements following a float.

  • Robert Nyman says:

    Patrick Fitzgerald,

    Absolutely, it's all about having options for different context.

    NICCAI,

    It's an interesting approach, although I personally shy away from a table display. The reason is that I strongly dislike the default table behavior of overflowing content and expanding beyond the original size to encompass it.

    Jermayn,

    Yes, different approaches for different situations.

    Kevin, Wojciech ZajÄ…c ,

    Ah, so that's your poison? :-)

    Rafael,

    Yep, that's one way to do it. Not a fan of the table thing, personally, as described just above.

    Kapitancho,

    Yes, I've been using it for quite some time too. However, it's not that good if you need to combine it with something else, say, a padding specified in a dynamic value such as <code>em</code>.

    Seraphim,

    I'm glad I gave you a new thing to try then. :-)

    Bruno,

    I do get what you're going for. Why I don't like that way of doing it, though, is for a couple of reasons:

    1. Dummy elements convey no semantic meaning.

    2. Your code ends up with a lot of, basically, superfluous elements that have no other meaning than clearing, ending up in larger file sizes/downloads.

    3. I want a layout where you can combine things without knowing the context, i.e. what's before or after the floated element, Unless you have a specified clear element after each float, this approach fails.

    However, I have to agree that <code>clear</code> doesn't work satisfactory on elements following a <code>float</code> , if you want to combine it with something like <code>margin</code>.

  • Abu says:

    Whoops, shouldhave read… time to get rid of all those

    <div class=”clearer”>

  • Abu says:

    I don't know where i've been all this time. Time to a bit of spring cleaning and get rid of all those .

    Thanks.

  • Robert—I have built a test case demonstrating the behavior I mentioned above.

  • Robert Nyman says:

    Shane,

    Thanks a lot! Very weird bug, but apparently <code>overflow: hidden</code> seems to be the way to go then.

  • Ole says:

    i like using the 3rd method. but in some circumstances i also use the oldschool , because i don't want to put extra divs surround every float.

  • bart says:

    I have noticed the following with the FNE method:

    * Outside container must be floated and therefore must have a width

    * If width is specified watch out for padding or borders

    * If width is not specified, container will shrink wrap around content

    * If width not specified and contained elements are floated to opposing sides container is stretched to 100%

    * Element following the container must CLEAR the float otherwise it will be shoved next to the floated container if room allows. If floated container has width of 100% or takes up 100% of the horizontal space then the following element will fall below the container. The following element's background and borders will show through the floated container

    * Element following the container will have to have a large margin-top in order for margin-top to take effect or margin-bottom has to be applied to floated container or appropriate padding to either element

    * The background of element following the floated container will show under the floated container

    * There are additional issues with IE6

  • Robert Nyman says:

    bart,

    Absolutely. Personally, I think I prefer the <code>overflow: hidden</code> approach. It has the least number of side-effects.

  • [...] How to clear CSS floats without extra markup – different techniques explained – ako zruÅ¡iÃ…Â¥ CSS floaty bez nadbytočného kódu [...]

  • Thanks for the article, Robert. This kind of summary is exactly what I was looking for. It's been awhile since I've had to deal with this kind of float problem, and all the solutions managed to fall out of my brain while I was busy with other things.

    I'm adding a weblog to my business site this evening. The older/newer articles navigation sits at the bottom of the page, and uses opposing floats to put list items side-by-side. Keeping this contained within the main content area was giving me fits. Thanks to you, <code>overflow: hidden</code> just saved my sanity.

  • Robert Nyman says:

    Adam,

    I'm glad it helped! :-)

  • Ryan says:

    Robert,

    This is perfect for what I have been needing. Traditionally, I created a class called "clear" and added that to a BR tag. Not exactly the best solution due to extra markup but it worked. Moving forward, however, I think I will try to use the overflow:hidden technique.

  • Robert Nyman says:

    Ryan,

    It is definitely a nice approach, so I hope you will be content with it!

  • [...] How to clear CSS floats without extra markup – different techniques explained. There are three major approaches: a) Floating the containing element as well, b) Using overflow: hidden on the container, c) Generating content using the :after CSS pseudo-class. A test-page for techniques. [How to clear CSS floats without extra markup] [...]

  • Tom says:

    Thanks for this summary, I've found very useful the 2nd method.

    No problems using it.

  • Jens Meiert says:

    I'm surprised – you mention the technique anyway, but don't refer to Anne's Super simple clearing floats (or the spec, respectively)?

  • Robert Nyman says:

    Tom,

    I'm glad it works for you.

    Jens,

    Surprised that I don't refer to Anne's post? Lots of people have already written various posts on this on the Internet, I can't refer to them all (especially not if their respective posts haven't been the ground for my post here).

  • [...] How to clear CSS floats without extra markup – different techniques explained. There are three major approaches: a) Floating the containing element as well, b) Using overflow: hidden on the container, c) Generating content using the :after CSS pseudo-class. A test-page for techniques. [How to clear CSS floats without extra markup] [...]

  • [...] How to clear CSS floats without extra markup [...]

  • [...] How to clear CSS floats without extra markup – different techniques explained. There are three major approaches: a) Floating the containing element as well, b) Using overflow: hidden on the container, c) Generating content using the :after CSS pseudo-class. A test-page for techniques. [How to clear CSS floats without extra markup] [...]

  • [...] Существуют различные техники клиринга плавающих элементов без дополнительной разметки. Во-первых, использовать float для родительского элемента. Во-вторых, использовать overflow:hidden для родительского элемента. Ð’-третьих, генерировать контент с помощью псевдо класса :after. Их работу можно проверить на тестовой странице. [How to clear CSS floats without extra markup] [...]

  • gcyrillus says:

    hello,

    display:table; can be used in some cases if IE layout is active and overflow not usable, when navigator understand this rule , the element clears itself from floatting elements. (just like a real table).

    (overflow clears from beside too if space wild enough just like 'layout' in IE).

    (to use something similar to display:table;

    in IE : display:inline-block; for inline elements and display:inline; + zoom:1; for blocks elements .. can help to vertical-align blocks and get a min-width and min-height for IE6 as well)

    The clear both is very useful too and always works , to avoid it to interfer with other areas of the page , you can set the container to position:relative;

    Clear:both , right or left; will then only interact into that ancestor

    set as position :relative;

    If you want to clear an element in your main content , and not fall under your menu (or whatever colum ) already set floatted , it's a good option too.

    (excuse my average english )

    GC

  • Robert Nyman says:

    cyrillus,

    Thanks, it's always good to have alternatives.

  • [...] How to clear CSS floats without extra markup – different techniques explained – Robert’s talk (tags: css reference tips web_design) [...]

  • [...] time ago, Robert Nyman wrote a post explaining a few ways to clear CSS floats without extra markup. The post is great as an overview of some different techniques for clearing your floats. There are [...]

  • Xeito says:

    Hi all.

    First of all congratulations for the article. I think floats is one of the major causes of headaches a CSS designer can find.

    Since I found it, I prefer the overflow solutions. I've used overflow:auto, but from now I'll use overflow:hidden.

    For the autor: I'm trying to adapt your article to spanish. I'll put it in my blog Recursos Flash if you give your permission.

    Best regards.

  • Robert Nyman says:

    Xeito,

    Absolutely, feel free to translate. Please just make a note in the beginning to this original article and a link to it.

  • [...] ” When using floats in CSS, without a doubt you have encountered the interesting effects it will have on the following content. Here I will show you different ways to clear floats without any extra mark-up.” How to clear CSS floats [...]

  • [...] How to clear CSS floats without extra markup – different techniques explained. There are three major approaches: a) Floating the containing element as well, b) Using overflow: hidden on the container, c) Generating content using the :after CSS pseudo-class. A test-page for techniques. [How to clear CSS floats without extra markup] [...]

  • [...] sur les avantages et inconvénients de ces trois techniques, je vous invite à jeter un oeil chez Robert Nyman et chez Florent Verschelde pour tout savoir sur les marges et contexte de [...]

  • [...] floats can be a tricky business and the tendancy is to use extra markup. This post from Robert Nyman looks at the pros and cons of various techniques. [...]

  • [...] How to clear CSS floats without extra markup – different techniques explained When using floats in CSS, without a doubt you have encountered the interesting effects it will have [...]

  • Artyom Shalkhakov says:

    Thank you very much.

    This is very handy. ^_^

  • Robert Nyman says:

    Artyom,

    You're welcome!

  • [...] How to clear CSS floats without extra markup – different techniques explained. There are three major approaches: a) Floating the containing element as well, b) Using overflow: hidden on the container, c) Generating content using the :after CSS pseudo-class. A test-page for techniques. [How to clear CSS floats without extra markup] [...]

  • [...] ?????????? ????????? ??????? ???????? ????????? ????????? ??? ?????????????? ????????. ??-??????, ???????????? float ??? ????????????? ????????. ??-??????, ???????????? overflow:hidden ??? ????????????? ????????. ?-???????, ???????????? ??????? ? ??????? ?????? ?????? :after. ?? ?????? ????? ????????? ?? ???????? ????????9. [How to clear CSS floats without extra markup10] [...]

  • [...] How to Clear CSS Floats Without Extra Markup: Different Techniques Explained – Robert Nyman [...]

  • [...] How to clear CSS floats without extra markup – different techniques explained. There are three major approaches: a) Floating the containing element as well, b) Using overflow: hidden on the container, c) Generating content using the :after CSS pseudo-class. A test-page for techniques. [How to clear CSS floats without extra markup] [...]

  • [...] ???????????????????????????????3?????????? a) ?????????  b) ???????? overflow: hidden  c) ??:after???css??? [How to clear CSS floats without extra markup] [...]

  • [...] Then along came floats which most of the people are using today. We can use any element we want to, but floats aren’t really for the fainthearted. On surface it seems pretty basic, but the complex functionality behind can make seasoned developers look dumbfounded at their screens. Also, one of the downsides with floats is needing to clear them through extra clear elements or, better, clear CSS floats without extra markup. [...]

  • [...] sur les avantages et inconvénients de ces trois techniques, je vous invite à jeter un oeil chez Robert Nyman et chez Florent Verschelde pour tout savoir sur les marges et contexte de [...]

  • It’s an old article, but it’s been really usefull to me.
    Thank you!

  • Robert Nyman says:

    Noemi,

    Good to hear!

  • [...] Then along came floats which most of the people are using today. We can use any element we want to, but floats aren’t really for the fainthearted. On surface it seems pretty basic, but the complex functionality behind can make seasoned developers look dumbfounded at their screens. Also, one of the downsides with floats is needing to clear them through extra clear elements or, better, clear CSS floats without extra markup. [...]

  • [...] ?????????? ????????? ??????? ???????? ????????? ????????? ??? ?????????????? ????????. ??-??????, ???????????? float ??? ????????????? ????????. ??-??????, ???????????? overflow:hidden ??? ????????????? ????????. ?-???????, ???????????? ??????? ? ??????? ?????? ?????? :after. ?? ?????? ????? ????????? ?? ???????? ????????. [How to clear CSS floats without extra markup] [...]

  • [...] ?????????? ????????? ??????? ???????? ????????? ????????? ??? ?????????????? ????????. ??-??????, ???????????? float ??? ????????????? ????????. ??-??????, ???????????? overflow:hidden ??? ????????????? ????????. ?-???????, ???????????? ??????? ? ??????? ?????? ?????? :after. ?? ?????? ????? ????????? ?? ???????? ????????. [How to clear CSS floats without extra markup] [...]

  • [...] Clearing CSS Floats – different techniques explained: http://www.robertnyman.com/2007/04/12/how-to-clear-css-floats-without- extra-markup-different-techni… [...]

  • [...] ?????????? ????????? ??????? ???????? ????????? ????????? ??? ?????????????? ????????. ??-??????, ???????????? float ??? ????????????? ????????. ??-??????, ???????????? overflow:hidden ??? ????????????? ????????. ?-???????, ???????????? ??????? ? ??????? ?????? ?????? :after. ?? ?????? ????? ????????? ?? ???????? ????????. [How to clear CSS floats without extra markup] [...]

  • [...] Làm th? nào ?? xoá float CSS mà không c?n t?i markup thêm – các k? thu?t khác nhau l?n l??t ???c gi?i thích. Có 3 ph??ng pháp chính: a) Float c? các y?u t? ch?a, b) dùng overflow: hidden trên container, c) T?o n?i dung dùng l?p gi? CSS :after. M?t trang th? nghi?m k? thu?t. [Làm th? nào ?? xoá float CSS mà không c?n ??n markup thêm ] [...]

  • [...] How to clear CSS floats without extra markup – different techniques explained. There are three major approaches: a) Floating the containing element as well, b) Using overflow: hidden on the container, c) Generating content using the :after CSS pseudo-class. A test-page for techniques. [How to clear CSS floats without extra markup] [...]

  • [...] How to clear CSS floats without extra markup – different techniques explained. There are three major approaches: a) Floating the containing element as well, b) Usingoverflow: hidden on the container, c) Generating content using the :after CSS pseudo-class. A test-page for techniques. [How to clear CSS floats without extra markup] [...]

  • [...] How to clear CSS floats without extra markup - Robert Nyman [...]

  • Wasif Hyder says:

    [...] How to clear CSS floats without extra markup - Robert Nyman [...]

  • Serj says:

    Thanks! Very helpful!

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>