I'm currently on parental leave till September 1st. Until then, I will not be available to read comments, e-mails, tweets and Facebook messages.

If you are interested in my writings, please subscribe to my RSS feed and follow me on Twitter.

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!

68 Comments/Reactions

  • #1 Phil Thompson
    April 12th, 2007 at 12:19

    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.

  • #2 Richard Mulhern
    April 12th, 2007 at 13:09

    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

  • #3 Chris
    April 12th, 2007 at 13:56

    Thanks for summarizing these methods!
    Like Richard I often use overflow:auto;.

  • #4 Andreas
    April 12th, 2007 at 14:08

    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

  • #5 Jeroen Mulder
    April 12th, 2007 at 14:10

    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 overflow seems to be.

    I make one addittion to the generated content though and that is font-size: 0 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 zoom: 1 , with the occassional need to fall back to height: 1% 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

  • #6 Sam
    April 12th, 2007 at 14:30

    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.

  • #7 Bramus!
    April 12th, 2007 at 14:34

    Very nice overview Robert!

  • #8 Bram.us » Clearing CSS floats without extra markup
    April 12th, 2007 at 14:37

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

  • #9 Shane Shepherd
    April 12th, 2007 at 15:52

    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.

  • #10 Robert Nyman - author
    April 12th, 2007 at 16:50

    Thanks for your comments!

    Sam,

    That looks just fine! :-)

    Richard Mulhern,

    Good point, overflow: auto 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 overflow solutions, i.e. overflow: hidden as well?

  • #11 Jeff L
    April 12th, 2007 at 18:43

    I use the overflow: hidden and zoom:1 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.

  • #12 Joe
    April 13th, 2007 at 3:26

    Excellent article. Thanks you.

  • #13 DocZayus
    April 13th, 2007 at 5:04

    Thanks.

    I always love getting new CSS tips.

  • #14 Daily Links » Zazie@Tokyo
    April 13th, 2007 at 5:32

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

  • #15 Navdeep
    April 13th, 2007 at 8:14

    Nice article.

  • #16 Robert Nyman - author
    April 13th, 2007 at 9:32

    Jeff,

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

    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!

  • #17 Ärger mit CSS:float at trilodge computin blog
    April 13th, 2007 at 20:23

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

  • #18 Patrick Fitzgerald
    April 13th, 2007 at 21:43

    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.

  • #19 Duluoz» Blog Archive » Clearing Floats With ‘overflow:auto’ Universally
    April 13th, 2007 at 21:46

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

  • #20 links for 2007-04-13 « toonz
    April 14th, 2007 at 1:23

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

  • #21 NICCAI
    April 14th, 2007 at 2:14

    Lately I’ve been using:

    W3C: { display: table; width: 100%; }
    IE: { zoom: 1; }

  • #22 Jermayn Parker
    April 14th, 2007 at 3:41

    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.

  • #23 Kevin
    April 14th, 2007 at 4:49


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

  • #24 Wojciech ZajÄ…c
    April 14th, 2007 at 8:49

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

  • #25 Cubma » Blog Archive » Kan läsas i hängmattan
    April 14th, 2007 at 16:04

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

  • #26 Rafael
    April 14th, 2007 at 22:37

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

  • #27 Kapitancho
    April 15th, 2007 at 4:01

    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.

  • #28 Seraphim
    April 15th, 2007 at 5:03

    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!

  • #29 Bruno
    April 15th, 2007 at 17:28

    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.

  • #30 Robert Nyman - author
    April 15th, 2007 at 21:11

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

    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 clear doesn’t work satisfactory on elements following a float , if you want to combine it with something like margin.

  • #31 Abu
    April 16th, 2007 at 4:31

    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.

  • #32 Abu
    April 16th, 2007 at 4:32

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

    <div class=”clearer”>

  • #33 Shane Shepherd
    April 16th, 2007 at 17:54

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

  • #34 Robert Nyman - author
    April 17th, 2007 at 9:06

    Shane,

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

  • #35 Ole
    April 17th, 2007 at 11:08

    i like using the 3rd method. but in some circumstances i also use the oldschool <br class=”clear” />, because i don’t want to put extra divs surround every float.

  • #36 bart
    April 19th, 2007 at 23:02

    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

  • #37 Robert Nyman - author
    April 20th, 2007 at 9:04

    bart,

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

  • #38 Linky na víkend 57 na depi.sk – IT & Life Weblog
    April 21st, 2007 at 14:17

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

  • #39 Adam Messinger
    April 24th, 2007 at 23:39

    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, overflow: hidden just saved my sanity.

  • #40 Robert Nyman - author
    April 25th, 2007 at 9:17

    Adam,

    I’m glad it helped! :-)

  • #41 Ryan
    April 26th, 2007 at 18:34

    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.

  • #42 Robert Nyman - author
    April 26th, 2007 at 22:31

    Ryan,

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

  • #43 CSS Float Theory: Things You Should Know | Smashing Magazine
    May 1st, 2007 at 15:02

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

  • #44 Tom
    May 7th, 2007 at 12:49

    Thanks for this summary, I’ve found very useful the 2nd method.
    No problems using it.

  • #45 Jens Meiert
    May 7th, 2007 at 22:24

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

  • #46 Robert Nyman - author
    May 7th, 2007 at 23:02

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

  • #47 Web-Design Blog » Blog Archive » CSS Float Theory: Things You Should Know
    May 10th, 2007 at 22:30

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

  • #48 Best CSS tools of May
    June 4th, 2007 at 11:10

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

  • #49 CSS Float Theory at Advertising Zone – Way to Success
    June 13th, 2007 at 11:12

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

  • #50 Design For Masters » CSS Float в теории и на практике
    September 15th, 2007 at 16:12

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

  • #51 gcyrillus
    October 28th, 2007 at 1:57

    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

  • #52 Robert Nyman - author
    October 29th, 2007 at 8:53

    cyrillus,

    Thanks, it’s always good to have alternatives.

  • #53 links for 2007-11-26 « Amy G. Dala
    November 26th, 2007 at 15:17

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

  • #54 Improving Your Process: CSS Techniques Part 2 – Monday By Noon
    January 14th, 2008 at 16:04

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

  • #55 Xeito
    January 23rd, 2008 at 9:35

    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.

  • #56 Robert Nyman - author
    January 23rd, 2008 at 10:08

    Xeito,

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

  • #57 CSS Concept » Life Concepts about CSS Float Theory
    March 4th, 2008 at 17:35

    [...] ” 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 [...]

  • #58 CSS Float Theory: Things You Should Know
    April 21st, 2008 at 13:34

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

  • #59 » Rétablir le flux après des éléments flottants en CSS sans balise HTML supplémentaire « css4design : des css pour votre design html
    April 23rd, 2008 at 18:09

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

  • #60 How to clear floats without extra markup | What did you mean ?
    July 30th, 2008 at 11:51

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

  • #61 Mega Awesome CSS Resource List! | WebDevLounge | design, development, SEO and wordpress | articles, discussion and community
    August 3rd, 2008 at 15:08

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

  • #62 Artyom Shalkhakov
    August 28th, 2008 at 6:58

    Thank you very much.

    This is very handy. ^_^

  • #63 Robert Nyman - author
    August 28th, 2008 at 11:55

    Artyom,

    You’re welcome!

  • #64 CSS Float Theory: Things You Should Know | Evolution : weblog
    October 31st, 2008 at 6:45

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

  • #65 Valet – ???????????? ????, ??????? ? SEO, ????? ? ?????? ????? » Blog Archive » CSS Float ? ?????? ? ?? ????????
    April 12th, 2009 at 0:09

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

  • #66 WEB 3.0 » Blog Archive » ¿Así que querías saber de CSS?
    April 18th, 2009 at 2:23

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

  • #67 CSS Float Theory: Things You Should Know | WEBDESIGN FAN
    August 26th, 2009 at 2:35

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

  • #68 CSS?????(float)????? – ????
    February 2nd, 2010 at 10:15

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

Write a comment

Twitter reactions

Share your thoughts:

HTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> . If you want to display code examples, please remember to write &lt; for < and &gt; for >.

Comment preview