Simple Clearing of Floats

Tweet

Without wanting to stray too deeply in Simon and Stuart’s technical CSS territory, I thought this was worth noting.

For all it’s many advantages, sometimes it’s the little things that CSS layout makes difficult that really get to you. Clearing floated elements is a good example.

The Problem:

One of the simplest and most common layout structures involves the placing of a small, set-width DIV — perhaps navigation, a quote or a bio — within a larger wrapping DIV that contains the remaining content. In a markup this might be something like:

<div id="outer">
 <div id="inner"> <h2>A Column</h2> </div>
 <h1>Main Content</h1>
 <p>Lorem ipsum</p>
</div>

We can set the width of ‘#inner’ (let’s say ‘width:20%’), but, being a block level element, the main content will always wrap beneath, unless we float it (either left or right). Here our classic problem begins.

If ‘#inner’ is shorter than #outer, all is well.

However, if ‘#inner’ grows taller than it’s wrapping parent, it breaks through the bottom edge of ‘#outer’. It’s as if ‘#outer’ forgets it’s supposed to be keeping tabs on what ‘#inner’ is doing as soon as you float it.

As we can’t always control the amount of content in these DIVs, it certainly presents a problem. Here’s a typical example of the problem in action. (Thanks to Pixy for the neat little content-gen script).

The Solutions:

a) The Markup Method: The first and W3C-recommended approach is a little ugly – extra markup. At the very end of your content, toss in a cleared element – typically something like <br style="clear:both"/>. It’s the HTML equivalent of wedging matchsticks into your window frame to jam a window open. This works, but ‘dirties your page’ with stuff that only exist so it renders properly.

b) The Aslett/PIE Method: Less than 12 months ago Tony Aslett working with PositionIsEverything.com came out with a new method so diabolically clever that they had to have been sitting in a fake island volcano, stroking a large white cat and laughing fiendishly when they thought of it.

You’ll need to read the tutorial to get the full story, but, in short, they use a little-known, rarely-used pseudo class (:after) to place a hidden, cleared full-stop after the content. Combined with a sprinkling of hacks, this works beautifully – but gives me a headache over my left eye when I think about it.

c) The Ordered List Method: Last October Steve Smith from Orderlist.com published a slightly simpler method. Again, read his tutorial to get the low-down, but in short, his method involves ‘Floating nearly Everything’ (FnE), which naturally enough includes the outer DIV. This can have a considerable effect on the way your design stacks and as Steve says ‘it takes a little more tweaking’ but in general this method seems a little more robust to me.

d) That was my ‘current state of play’ until last week when SitePoint Forum’s own CSS Guru, Paul O’Brien, nonchalantly pointed out that adding a ‘overflow:auto’ to the outer DIV did the trick.

‘Rubbish’ I thought to myself.

Half an hour of testing later, I was amazed to find Paul was 100% correct – as this example shows. It seems that reminding the outer DIV that it’s overflow is set to ‘auto’, forces it to think “oh yeah.. I’m wrapping that thing, aren’t I?”.

This fact is so boringly simple that it’s hard to know if thousands of developers are well aware of it, but never thought to mention it. I know I showed the example page to four CSS-savvy SitePoint colleagues and all shock their heads, blinked slowly and said “Whaa…?” (or something similar).

From my testing, it seems to work identically in virtually every browser. Even IE4 seems to love it – only NS4 freaks out, and I’m not totally convinced a few hacks couldn’t get that working.

We haven’t had time yet to thoroughly test this method under rigorous match conditions, but so far there don’t seem to be any major drawbacks.

Certain combinations of margin and padding can force internal scrollbars. If you can’t ‘massage’ them away, we found ‘overflow:hidden’ has virtually the same effect without the scrollbars. The only drawback of ‘hidden’ seems to be the cropping of some images if they’re placed lower in the page.

Both issues seem very manageable.

Nice work, Paul.

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • http://www.generationphp.net Xenon_54

    Not working if you place #inner AFTER your contents. The reason why I puts #inner after my contents is that people prefer to have a direct access to the contents rather than to have to glance through all your menu. You just have to test by trying to navigate using the tab key.

    But a big “bravo” to you because I do not remember having already seen this tips before.

  • Anonymous

    Not working if you place #inner AFTER your contents

    Hi, the float will still be cleared if you place #inner after the contents but obviously still within the parent container (#outer)
    e.g.

    
    <div id="outer">
     <h1>Main stuff</h1>
     <p>Lorem ipsum</p>
     <div id="inner"> <h2>A column</h2> </div>
    </div>
  • Jop

    That’s a great solution and works pretty well – In firefox after you have clicked the ‘very long’ link you have to explicitly focus (click) the content to be able to use your mousewheel to scroll. This doesn’t happen in Example one and it seems to work ok in IE.

  • http://www.assemblysys.com/dataServices/index.php mniessen

    I’m must say that even the example 1 from Pixy displays fine in IE6 SP1 under WinXP Pro. I had to view the page in Firefox to see what the problem was.

  • http://www.generationphp.net Xenon_54

    Hi, the float will still be cleared if you place #inner after the contents but obviously still within the parent container (#outer) e.g.

    I found out that I was using a container for my contents (#content)

    That explains everything…

  • http://www.iangordon.us Ian R. Gordon

    OMG! Paul is a friggin’ genius! Congratulations you CSS Guru you! This will save me lots of time and headaches…

  • http://www.sitepoint.com AlexW

    I’m must say that even the example 1 from Pixy displays fine in IE6 SP1 under WinXP Pro. I had to view the page in Firefox to see what the problem was.

    mniessen, as long as you set the outer DIV to width:100% in IE it will always clear the inner box automatically. This is a bug, according to the W3C, but a pretty useful one.

    Getting Firefox, Opera, Safari to behave the same way has been the problem.

  • http://www.aplus.co.yu/ aleck

    Unfortunatelly, this is not really usable at the moment because of gecko bug with overflow:auto.

    If you have absolute layer, positioned over overflow:auto element, FF will cancel :hover, :focus and similar as soon as your mouse enters the overflow:auto area.

  • Anonymous

    Hi Aleck,

    Do you have an example of what you mean as I can’t seem to replicate it. I’ve positioned an absolute element over the auto element and the only elements that are hidden are of course the elements under the absolute element (assuming the z-index is higher of course).

    Ive tried it with nested and non-nested absolute elements so I’m probably missing something here.

  • Tom

    damm, what a stupidly simple fix. And here I was trying to get min-height working to fix these issues.

    Cheers

  • ydnar

    In my tests where I’ve been using a modified p.i.e. method:


    .clearme:after
    {
    content: ".";
    display: block;
    visibility: hidden;
    clear: both;
    height: 0;
    font-size: 0.1em;
    line-height: 0;
    }

    The above CSS is pretty robust, containing all manner of floated/non-floated content. Switching to overflow: auto breaks the layout on IE5, throws up scrollbars in Firefox.

    However, using overflow: hidden; does the trick. The container div has an explicit width and no explicit height, and it just works, even in IE5 (Win/Mac).

    The only problem with this solution is that using negative margins to push things around inside the container div results in their being clipped in Moz/Safari/IE6 (though oddly enough, not IE5, which I have to guess is misinterpreting overflow: hidden on a display: static div.

  • Chris

    Doesn’t work in IE6. :(

    Setting the containers width to 100% doesn’t help either (horizontal scroll bar in most cases).

    What am I missing here?

  • Bjorn Carlsson

    Just a note/word of warning: instead of setting width:100%; for the width of #outer, I tried height:1%; …

    Which seem to work ok in IE6 and IE5.5, but totally collapses the height (to 1%) in IE5.0

    Thanks for the article, this fix is just so brilliant and strikingly simple!

  • d4ddyo

    This *is* good news, except I am unable to get it working for IE/Mac. I’ll have to give the overflow: hidden; method a shot.
    Thanks!

  • http://diigital.com cranial-bore

    It seems to me (and I haven’t had time to test this thoroughly) that overflow: auto will effectively bring the bottom of the containing div to below ALL floats on the page in Opera (7.54).
    This is also how Firefox behaves when you use a clear DIV — unless the clear DIV is contained within a floating DIV it will clear all the floating DIVs on the page.

  • http://www.dustindiaz.com polvero

    i’m still going to be floating my parent div. it’s been working and i’ve never really found there to be any ‘tweakin’ that needs to happen. since it also looks like there’s still bugs that need to be worked out, I’m sticking with what still works.

  • Zoe

    Regarding the Gecko bug, here’s the bugzilla entry with examples:
    https://bugzilla.mozilla.org/show_bug.cgi?id=125386

  • Anonymous

    Yes there are some bugs with overflow, especially with mozilla. This obviously isn’t a definitive answer but just another piece of the jigsaw that will work in situations such as the main example above.

    It does however seem to be a valid use and part of the overflow spec in that elements with overflow set will have their height calculated to include floats.

    http://www.w3.org/TR/CSS21/visudet.html#q22

    In a lot of simple situations such as floating an image with text alongside that doesn’t extend pass the image then it seems to work well.

    More complicated constructs can cause it to fail but mainly due to browser bugs than a fault with the concept.

    It’s still worth knowing about even if for interests sake only.

  • http://www.sitepoint.com AlexW

    Absolutely, Paul and certainly more than just interest value. For simpler layout components, it has to be the easiest solution to implement. And as so few people have been aware of this behavior till recently, I’m expecting that new eyes will bring some more understanding to some of the bugs showing up in more complex situations.

  • http://www.gamecubecheats.info jag5311

    Paul has helped me out on SO many occasions I have lost count. He is very good at what he does and this continues to show it.

    I have been using
    for SO long, this might be my new best friend :)

    Thanks for sharing.

  • Roger

    Overflow:hidden causes Netscape 7.1 to hide my whole content! Overflow:auto causes Firefox to display artefacts on a very long page’s bottom.
    Best example is one of my sub-pages http://mowlog.blogspot.com/2004_12_01_mowlog_archive.html

  • bhaktano1

    awesome stuff! thanks for sharing.
    I was looking at the code for the examples, and saw a <kbd> tag. I have not idea this existed and what it did. I looked it up but w3c says it “Indicates text to be entered by the user.” I’m still in the dark though.

  • hanumani

    Looks great! Can it be used for 3 column? I’m trying that but it’s not working. Any ideas?

    thanks,
    Jacob

  • http://www.sitepoint.com AlexW

    hanumani, I mocked up a quick test when I first found this out, and it seemed to work.

    I wanted the content to appear in the code before either columns, so I put the MAIN and LEFT column into their own wrapper DIV, and floated MAIN right. If you then set the wrapper to, say, 75% and float it left, any following RIGHT column will slot into the remaining the 25%.

    The use of the wrapper DIV isn’t completely semantically sound, but it was the best solution I could find in 20 minutes of toying with it.

  • scattermachine

    Paul ROCKS… Again!

  • http://www.aplus.co.yu/ aleck

    Paul, the bug is with event firing (I think). Take a look at this example: http://www.aplus.co.yu/css/ffoverflowbug/

    It’s nested list transformed into pop-up menu plus a text block with overflow:auto applied. Move over second item and submenu will show.

    Now, you can move your mouse over submenu part as much you like – if you stay clear of the text block, the submenu will stay open (visible). But as soon as you move the mouse over the block, the submenu goes away. It’s like :hover is canceled.

    This does not happen in Opera or IE. This example of course does not work in IE, but I have developed drop-down menu (www.aplus.co.yu/adxmenu/intro/) like this with some helper code for IE so I know it does work correctly in IE.

  • http://www.dynamicsitesolutions.com/ Kravvitz

    I prefer the Aslett/PIE method.

    In response to Zoe and aleck, that Mozilla Gecko engine bug is fixed in version 1.8, which is used in the beta versions Firefox 1.1. Hopefully, a new version of Netscape 8.x will be released shortly after the release of Firefox 1.1.

  • kodeman

    From what I have tested, the main things that need to exist in your style rules for the container are the following:

    You must use ‘overflow: hidden;’ so that IE 5 Mac will clear the floats

    You must specify at least one dimension explicitly, either height or width. I recommend using width over height, so the container can expand vertically as needed, and since you typically will be able to control horizontal space easier, especially if you use margins or padding to limit horizontal space available for the container to expand into (like, say, having width of 100% on the container and using 4% left and right margins to make the container ‘flexible’).

    You may use border-bottom OR margin-bottom to trigger the bottom of the container expanding down below the floats. I personally use a 1px bottom border AND a -1px bottom margin to prevent that unwanted 1px ‘line’ that a border might make (especially useful if you need to match up backgrounds on the container and another block below it).

    I have also found that the overflow method is not always the best solution. Sometimes it is better to just put floats inside a container that is also floated. Obviously, when using float-in-float, always set at least one dimension (width or height), and always add ‘display: inline;’ to swat a bunch of IE float-related bugs.

    A mix of the overflow method and the float-in-float method ought to take care of any float-clearing needs you have, and both work cross-browser with style rules that don’t require CSS filters, code forks, extra markup, or other ‘hackery’.

    Hope this helps.

    Standard Disclaimer: YMMV. I may have forgotten something, and I may be hiding something, but I am always doing something, and that is more than the lesser of us do who remember everything, have nothing to hide, and do nothing with that blessing.

    Cheers

  • Dan

    after 45 seconds of testing i managed to break it in IE6 for windows – go figure..

    http://www.pages.drexel.edu/~dja29/miscstuff/clearedContentBug.JPG

  • kodeman

    Dan,

    well, if the code stated as being applied to #outer in your jpeg is actually what is being applied, then you missed some crucial points:

    1. you must explicilty specify a dimension along with the overflow:auto;

    2. you must specify either a border-bottom or margin-bottom, or both

    the first part of the trick is that you need at least one dimension specified for some browsers to apply layout semantics to a block with the overflow property set. don’t ask me why, its an enigma.

    the other part of the trick is that setting the bottom border or bottom margin of the block is what causes the bottom edge of the container to clear the floated child elements when your overflow is set. that behavior is buried in the css 2 spec somewhere.

    the last part of the trick is to set overflow to auto, scroll, or hidden (reportedly). we go with auto becuase scroll gives you scrollbars (duh) and hidden not only may cut off child elements who straddle the borders of the parent, but also triggers bugs in IE5 Mac and maybe others. a nice side-effect of using auto is that you get no initial scrollbars, but if some extra-long line of text sneaks into this element, scrollbars will appear and let that content be accessible instead of just being cut off or otherwise escaping their containing block. auto is pretty much all upsides :)

    the moral of the story is to use ‘overflow:auto’, specify either ‘width’ or ‘height’, and add a ‘border-bottom’ and/or ‘margin-bottom’ to complete the technique.

    now, i’m going to go rest my aching noggin ;)

    cheers.

  • Jon B

    I have been using this technique and seem to always encounter problems in IE6 with XHTML Trans doctype – I haven’t pegged that exact cause yet, but basically it has no effect in IE6 whereas it is working in every other Win/Mac browser I could test – weirdness, depressing weirdness

  • http://zepfanman.com RockOfVictory

    I’ve been searching for a fix to another problem that you can see revealed in your example, as well (but no solution). Notice that the left border of the outer kbd box is cut off? I’m having a similar problem with my floated containers and other lines “intruding” into the box. See the floated right box towards the bottom of my beta page: http://zepfanman.com/beta

    Thanks!

  • Jade

    Just a note, for me, this doesn’t seem to work in Opera 6 for mac osx. At least that’s what Browsercam shows me. Anyone’s mileage differ?

  • ChooseToLive

    I’m trying to implement this on a page redesign, and it works GREAT in Firefox. However, I can’t get this or *anything* to work in IE6 (not even the old standard clear:both). Can anyone tell me what I’m doing wrong? My test page is here: http://www.passionbreedsfollowers.com/julie/test/3col.shtml

    Here’s the code for my #outer div:

    #outer {
    border-left-width: 140px;
    border-left-color: #66000E;
    border-left-style: solid;
    border-right-width: 140px;
    border-right-color: #dcdcb6;
    border-right-style: solid;
    padding-left: 25px;
    padding-right: 25px;
    padding-top: 40px;
    padding-bottom: 20px;
    background-color: #dcdcb6;
    width: 370px;
    margin-top: -3px;
    overflow:auto;
    border-bottom:1px;
    margin-bottom:-1px;
    }

  • ChooseToLive

    Re: my prior post, I just went ahead and floated the relevant divs, which was ultimately a lot less trouble than I thought it would be, so that’s good. :) The overflow:auto works great until I bump into the margin/padding issues mentioned – I have some very precise float widths set and Firefox seems to want to add some padding where it’s not supposed to. So I guess I’m off to try the PIE fix, though I like this one so much better for its ease and simplicity.

  • http://www.sitepoint.com AlexW

    Jade: I’d take your word for it on Opera 6. We’ve found Opera users are generally pretty committed to the browser, and see it as their duty to upgrade whenever a new version is available, so I wouldn’t give older Opera versions with the same attention as, say, older IE users.

    ChooseToLive: As you seem to have discovered, the overflow method is very useful, but weirdness can creep in as layouts get more complex. I know that the new ‘Feature article box’ on SitePoint’s cover gave me issues. I found Firefox calculated the distance fine until I narrowed the window past a certain point — where it collapsed to half it’s width. Still don’t know why.

    Basically I take the overflow method as ‘first bullet’ and if I get into trouble I’ll just toss a ‘class=”clearfix”‘ on the DIV instead.

  • http://www.johandahlstrom.se Johan Dahlstrom

    Absolutely wonderful Paul! You go :)
    Missed that post where this happened, so thanks for the tip Alex.

  • Veeru

    Sorry guys, something really off the topic – i kinda like the bottom advertisement on this page, i would really love to have something like that for my site. I am still new to web design, any help will be really appreciated.

    Thanks

  • http://www.sitepoint.com AlexW

    Veeru, it’s a method we’re testing and it’s been operating for about a week now. We’ve written it from scratch and we’re obviously still testing it. It’s all Javascript so you’re welcome to pull it apart. There is some discussion about it here.

  • Veeru

    Thanks alexW, well let me see what i can dig from there – Cant wait to learn to do that (if i can learn ! :)

  • shannon

    i’m having problems with “overflow: hidden” and “overflow: auto”, and it doesn’t make sense. When i apply it to a float, a little 20px padding appears (FF only) on the right side – it doesn’t show up in the DOM under computed styles. It looks like FF is making room for a scrollbar, but that doesn’t make any sense in the first case since :hidden inherintly implies no scrollbars. Once i take :hidden or :auto out, it displays correctly. The computed styles for margin, border, padding, and width come through identical in both cases, but visually that is not true. Width, bottom border were also set. Anyone have that?

  • shannon

    btw- when i refresh, the phantom padding disappears. but if i navigate away and then back ot the page it comes back.

  • http://www.sitepoint.com AlexW

    Shannon, have you got it anywhere where we could see it?

    I’ve found beta 1.5 has been pretty skittish, so it may well be a temporary thing.

  • Pingback: Sheriar Designs Blog » Blog Archive » Faux Columns :: The Next Generation

  • Pingback: Sheriar Designs: Impeccable Code | Beautiful Design » Blog Archive » Faux Columns :: The Next Generation

  • Pingback: ebyblog » Blog Archive » links for 2006-01-02

  • andyhume

    March 2003:

    http://www.mezzoblue.com/archives/2005/03/03/clearance/

    Still a great tip though! And worth repeating for to encourage people not to dump extra unsemantic markup in their code solely to clear floats. :)

  • andyhume

    Hmm.. that should of course read March 2005! (sorry!)

  • Pingback: RiK0’s Tech Temple » Inner float…. (CSS)

  • someguy

    It’s unlikely that anyone will read this far down, but I found that the combination that works for both IE 6 and Firefox 1.5 is


    overflow: auto;
    height: 100%;

    Overflow does it for firefox and the explicit height does it for ie.

    Cheers.

  • Anonymous

    nice work someguy.. This really helped me when clearing floating div with Firefox, IE, and Netscape..

  • Strayer

    Holy ..
    Soooo many times I had this problem and this ..damn…simple…thing… resolves it?

    Mr. Paul O´Brien – I love you.

  • Justin

    Son of a…….okay, I’m going to go find a sharp object and pound my head against it for a while….

  • Gordon

    Doesn’t seem to work in i.e. 6 if my outer div is a fixed width and floated left, and my inner div is a fixed width and floated right.

    I use the clearfix method successfully on other parts of the site, but no luck in this situation.

    Gordon

  • Terry

    Awesome. These little things are killer.

  • Bjorn

    Whoohoo thanks! Was looking for this quite a while!

  • Thomas

    I cannot get this to work at all in FF, I have tried numerous solutions and nothing seems to work, I get scroll bars with auto, content cut off with hidden, but works fine in IE, except that I always use FF. Anyone else crack the FF issues?

  • Pingback: chasingdaisy.com » Blog Archive » Links for 2006-06-11

  • Bob

    This fix works great on my computer (and on all the browsers I tested it on), but when I put the page online, and the server is slow, sometimes the content is cut off (overflow: hidden) or scrollbars show up (overflow: auto) when using IE 6. When I refresh the page it works o.k. again. Anyone else has this problem? I’m sticking with the good old clear:both html trick ;)

  • Joel A. Burdick

    Ouch! That was clever!!
    This will save me from making ugly code and redundant tweaks in the future!!

    Thanks!!
    -Joel

  • woe

    Just when you thougth you had all the triks ironed out!

  • Dave

    Very nicely done! I’ve been looking for a solution for quite some time now!

    David Levin

  • Matt

    Awesome! This fixed the background issue I was having with IE7 with my work’s site. http://www15.serrahost.com/fs4sportscom/StoreFront.bok Its still not working in IE6, but I’ll figure it out. :-)

  • PinkFu

    someguy Says:
    January 20th, 2006 at 1:08 pm

    It’s unlikely that anyone will read this far down, but I found that the combination that works for both IE 6 and Firefox 1.5 is
    overflow: auto;height: 100%;

    Overflow does it for firefox and the explicit height does it for ie.

    Cheers.

    It works better as:

    overflow: auto;
    _height: 100%;

    This way FF ignores the height (which can get screwy if set to 100%) and IE 6 is all WTF? *ignore* to the overflow.

  • akella

    There is one little problem in Firefox with this approach. User can select all the content with just one click.

    Try clicking to the left of the columns here
    http://www.mezzoblue.com/tests/float-auto/index-auto.html

  • spoison

    awesome !!
    overflow woirks perfect thx a lot dude and happy styling !

    spoison

  • spoison

    awesome !!
    overflow works perfect thx a lot dude and happy styling !

    spoison

  • alex

    I’m baffled by the Aslett/PIE method.
    They contrived it ‘because CSS is supposed to minimise bloating of HTML for design purposes’
    But they end up bloating the CSS to the extreme!
    Yes, the screen reader doesn’t have to read another <br style=”clear:both;” /> (which isn’s a huge chore is it?)- but we do have out bandwidth chomped by ugly, hard to read CSS which seems to be against everything it was designed for.
    But I guess the main point of the article wins- simplicity rules- and the overflow:auto method does the job with elegance.

  • Nicole Sullivan

    I’ve found that using overflow:hidden to clear floats causes some very strange printing bugs in Firefox. My best guess is that the overflow hidden limits the box size to the edge of the page, any overflow isn’t printed.

    I decided to remove the float and the clear for the print version and specified it in the print stylesheet. Perhaps with overflow auto I wouldn’t have needed to? I’ll have to test it, but in any case it seemed to me that a simplified layout for print was appropriate.

    Thanks for the technique,
    Nicole

  • Brian

    Right-clicking a div with overflow:auto; results in an aesthetically displeasing border appearing around the element.

    The fix: ‘outline:0;’

  • tip

    If you want to contain floated child elements in IE, you may also use zoom: 1;, which causes ‘hasLayout’. (Place in conditional stylesheet, since it is not valid css.)

  • Devoras

    Thanks so much Paul and Alex, have been using the Positioniseverthing workaround for a few years, but the overflow is so stupendously simple I think most of us missed it since us developers probably assumed that overflow defaulted to auto in the firstplace.

    Brian and tip, you’re life savers too… I never realised about the outline until I read your post and clicked myself to see the ugly border, and tips tip just fixed a nasty IE problem that hasn’t appeared in all my other sites I’ve built before. Conditional stylesheets are a given when Internet Exploder is concerned, thank crap for the

  • Anonymous

    bloody marvelous!

  • Rawllie

    I thought it was perfect with my Firefox 2.0.0.13 but then when I tried it in Safari 3.0.4 (for PC) it didn’t display my overlapping content. :(

    I want to optimize my site for Firefox, Safari and IE but have no idea what to do. Originally this was a table layout that I converted to CSS with ease, except for this stupid issue!

    http://www.nocturnalsojourn.org/fire/div-index.htm

    (see the sidebar? i also have the same issue when putting content into the area on the other side)

  • Anonymous

    Unbelievable

  • lucyconnuk

    When I use FF DOM Inspector to look at my page, a weird thing happens. The element which has overflow:auto doesn’t blink when selected using the DOM Inspector node list – neither do any of its children.

    Not a huge problem, but a bit strange.

  • jsherk

    That whole overflow:auto and overflow:hidden thing did the trick!!!

    Simple and effective!!!

    Thanks

  • markkra

    One more thing that overflow:auto does in FF is add the div to the tab order. It becomes a tabstop and shows a focus indicator when you tab around the page. I forget where I found it but you can creatively work around the issue by adding tabindex=”-1″ to the div in the markup (won’t validate) and set outline:none in the CSS.

  • Shannon Green

    No way… just… wow.
    THANK YOU SO MUCH.
    I always use a when I run into this problem… but this is so much better!
    Why does this need to be done? Is it a bug in just about every browser’s implementation of CSS, or does it fit the specification?

  • http://www.nicedeals.co.uk nicedeals

    I experience the same problem as mentioned by “lucyconnuk” but overall 10++ :)

  • Eamonn

    This is really unbelievable. Been coding pretty hardcore css/html for a few years now, and have always came up against this, and have been some pretty disgusting work arounds to solve it.

    Amazing stuff, this just saved me a chunk of time. I obviously need to read up some more on how ‘overflow:auto’ is actually defined.

  • paul

    the overflow:hidden or auto method is described in the 2006 CSS Mastery book

  • http://www.sitepoint.com AlexW

    the overflow:hidden or auto method is described in the 2006 CSS Mastery book

    This post is from early 2005.

  • www.cybernoxa.pl

    Man, as you said “Whaaa…” – why didn’t I think about it ;D

  • Debi

    i LOVE you!!!!!

    I had my page all laid out so beautifully in IE and was so proud of myself for my first completely tableless design. Then I looked at Firefox and just about cried. Now I don’t have to go back to tables ever again!!

  • Erin in awe

    I just got butterflies. Three years later for those of us just catching up to divs, this solution restores my sanity level. Maybe I’ll start eating again. Thank you thank you thank you!!!!!!!!! it IS BRILLiant!!

  • LazyAndroid

    And this is from 2005? Arggh, why did I not see this before? I allways used the positioniseverything method. Works most of the time but is very complicated. And I never remember how it works, so I have to look it up again and again.

    This is fantastic! Why isn’t this higher up in Google?

  • Matt

    I can’t believe this is from 2005! wow do I feel dumb. how many sites have I done with divs inside of divs to get around this when all I needed was a little overflow?? excuse me while I go bang my head against a wall for a couple hours.

  • http://www.clearwind.nl peach

    omg you doubted the words of P O’B?
    of course he is right.
    ;)

  • Bob

    THX, I tried so many different things to fix this and this is perfect!

  • Grammar Police

    “It’s” is not possessive.

  • Richard Dye

    Oh, hey. Awesome. I’m embarrassed not to have already known.

  • Laura Lipizzan

    I cannot believe that I have spent more than 16 hours online (about 8 of those hours at Mozilla sites) looking for a solution to this problem, and, finally, I came upon your site.

    Eureka !!! My Lipizzan.com site displays in Firefox now with its scrollbar. Before I used your solution, it was even difficult to scroll down with the Page Down key or the down arrow key.

    I used: overflow: auto; height: 100%;

    During all those 16 hours searching for a solution, it became known to me that my “home made” html from about 13 years ago (including subsequent, noncompliant tweaks) is totally outdated and not browser friendly to begin with. I do plan to redo the entire site in modern day standards for code . . . but, not right now.

    Anyway, you saved me. Thank you so much. I am going to put a link to your website on all of my websites.

    Do you take donations? I hope someone pays you for your intelligent, linear and brilliant analysis and solutions.

    And, if I may add more:

    your very clearly and thoroughly written, easy to follow instructions,

    for both CODE-COMPLIANT NEWBIES and the 78-45-35 RPM-VINYL RECORD-TYPES*,

    with the the technical and gory details optional for the reader.

    AAA+ to you !

    Laura Wiener-Smolka
    e m a i . . . .
    Lipizzan ^ hollinet ^ com

    * I’m one of the RPM type author/webmaster of 11 websites: 4 personal, 5 public agency/org, 2 commercial(the only ones I receive a few $ for — ha ha).

  • rambohoho

    hi, I’ve spent tones of hours working on this problem. but didn’t find a way to come out yet. this is the page I’m working on.
    http://bmk-innovas.com/new/aktuelles.html

    here ‘s the css page

    http://bmk-innovas.com/new/bmk.css

    I tried your resolution but then there will be scroll barr inside the white page. what I want is a scroll bar inside the window.

    maybe you know the answer. :-)

  • Tenzin

    hi rambohoho

    You can’t put all your content in topnav DIV with height of only 20px. Take everything out of TopNav DIV and correct our CSS. Nachher Ich schaue noch.

  • http://www.clearwind.nl peach

    btw it wouldnt be smart to build a layout and start out putting overflow:auto on all containers… as the layout will grow in complexity you’ll start to see scrollbars popping up allover the place, if you start using layout tools like out-of-flow positioning, negative margins etc.

  • Ricardo Zea

    I don’t know if anyone has noticed for more than 3 years, probably someone has mentioned it in a comment above somewhere and the author didn’t read it or doesn’t want to change it… but the demo and the actual quote about the solution say/use:

    “… ‘overflow:auto’ to the outer DIV did the trick.”

    And the current (8/11/08) CSS file uses overflow:hidden; and it still works.

    #outer {
    background-color:#fff;
    overflow:hidden;
    padding-bottom:0px;
    width:100%;
    -moz-border-radius: 0 0 15px 0;
    }

    Both work, of course :), but I just wanted to point this out. It’d probably be good to update the CSS file then?

    Bytes,

  • ezt

    another site which has a good explanation of the same thing:
    http://www.quirksmode.org/css/clearing.html

    I like to note that it’s not a 100% css solution, even though some people may think that(?). Sometimes you need to ADD a wrapping div in the html code, because it’s not always there already! Not that it’s a problem, besides i don’t believe in 100% css solutions anyway. To me, structure(html) and css go together. The layout of the page follows (or should follow) the structure of the html. This means i use floats instead of position:absolute. A page flow with a lot of positioning, seems to be less accessible/readible for blind people and such.

  • Noparanoia

    Oh GOD, thanks you, I was using spacers for years.

  • lionel87

    I found a ?new? solution for clearing floated divs in IE (all versions)

    div { width: 100% }

    since all divs are 100% width by default, this looks fine for me.

    to achive the same result on firefox, im using the old way (overflow:hidden/auto) with conditional comments to keep the source cleaner for IE

  • Rami

    the answer is simple, just use main wrappers, and wrap you divs carefully, i use main wrapper to wrap the header for example and the sub wrapper, and i use the sub wrapper to wrap the columns and the footer, it works 100% it’s a bit tricks because you have to make sure the sub warper background color matches the main wrapper one and make sure the borders are not messed up :D in other words it floats my boat

  • Sebastien

    Wonderful trick, thanks a lot!!!

  • Neena

    I’m doing this for very long time. So nothing new.

  • John Morris

    Dude,

    So stupid simple… works like a charm. Saved me a headache! Thanks!!

    John

  • Chris Gibson

    Neena, it’s great that you already knew this, but I haven’t read the post in which you bothered to share your knowledge with other people…? Could you perhaps post the link?

    This is an amazing tip, I can’t believe clearing floats is this easy. No more <div style=”clear: both”> and so on…

  • Nikos

    Brilliant – my understanding:

    Inner element(td/div/etc)=100% – content has to ‘push’
    outer element(td/div/etc)=overflow:auto – element has to ‘expand’

    Thank you!

    Nikos

  • Kevinjohn Gallagher

    Great Article mate,

    One thing i’d point out though is that the overflow:auto technique has been around for a very long time indeed. Infact, if i’m not mistaken, the very first JavaScript/CSS library i used from on Thomas Bratta used it extensively (and we’re going back almost 10 years now).

    I think you’re right, that it’s so shockingly simple that those of us using it for an eternity never though tot mention it, i have to say i was a bit surprised it wasn’t CSS101. But this is a GREAT article and the more people that know about these little things the better.

    Nice Job.

  • Jon Green

    Thanks a thousand-fold! This saved me some major headaches. :)

  • http://www.iangordon.us Ian R. Gordon

    IE support through conditional includes always seems to be a headache for developers, I for one, do it very last because I might change my mind and not support it, just give them a blank stylesheet.

  • derky

    EXTREMELY HELPFUL THNX!!!!!!!

  • effectwave

    This method (overflow:auto/ hidden) works great with the main wrapper div containing two more divs. But this doesn’t seem to work with a wrapper div containing three divs. This problem is only visible in Firefox. In IE everything works fine.

    I have created a page where there are two columns in the top div which work fine, but the three columns in the bottom div don’t align properly. Here is a URL to my website.

    http://www.webdesignmatching.com/ee/quotes.htm

    Any ideas?

  • Keli

    I LOVE YOU

  • http://www.sitepoint.com AlexW

    @effectwave

    That’s a strange little problem. Had a quick look and can’t pinpoint the exact issue. However, it seems feasible to rearrange your CSS to get the right result.

    Simply take out the BG color of the center div and the overlap is invisible. The BG color of the wrapper stretches with the columns fine. As long as you have 3 columns with the same BG color, this should be ok?

  • http://www.clearwind.nl peach

    I’ve just had an occassion where the overflow:auto worked unreliably in Firefox 2.
    I had no problems whatsoever in ff3 or any other browser but when I was doing a Quality Assurance round with Firefox2 I noticed that the clearing of a flexible-width footer’s contents failed while stretching the width of the viewport to certain points. seemingly random and only at 1% of all points you can drag the side of your browser.

    I swapped the overflow:auto for a PIE-style clearfix class and all was good again.

  • Robert B

    Using the "overflow: auto; height: 100%;" method, I noticed a small issue appear in both FF and IE. The entire page took significantly longer time to render, presumably waiting on all the code to load before it could calculate how much "100 percent" actually was. In my example the item floated is an image whose size is explicitly declared, followed by a line of text as a header and a paragraph element. In the default 1em font size the text elements together are not as tall as the graphic.
    <div style="overflow: auto; height: 100%;">
    <img src="myimage.jpg" style="float: left; border: 0; margin: 0 10 0 0; padding: 0; height: 96px; width: 96px;">
    <div style="font-weight: bold; font-size: 1.5em;">My Header Text Here</div>
    <p>My paragraph text here.</p>
    </div>

    What I found that helped was to enclose all of this in yet another <div></div> which in my experience cut the rendering delay down considerably.

    Has anyone else noticed this render time issue?

  • http://www.sitepoint.com AlexW

    That’s interesting to know, Robert. I’ll have to do some testing to check it out.

  • may

    “whaa…” so simple. it works! thanks =)

  • Anonymous

    Robert, if you are adding DIVs anyway, surely you may as well just make them clear: all divs and get rid of the problem that way?

    Frankly, overflow: auto was a major headache in IE6 rendering and I wish I hadn’t bothered. Give me the old fashioned clear: all method any day.

  • Alex M

    Thanks! Just used this on a project :)

  • http://www.abouttiyo.web.id Tiyo Kamtiyono

    It was simplest ever way, but we can not implement it on a sharing button where facebook like/send is also there. So picking the first method is good enough, just use a div, so there will be no out put that we don’t want to be appear.

  • http://onsman.com/ ronsman

    Thanks, Praveen: link updated.

  • Guest Speaker

    Assumption: ‘float’ is for wireframe layouts.
    Truth: ‘float’ is for content layout, not wireframe layout. Anything else is a hack.

    I’m not surprised you have to use hacks to use ‘float’ incorrectly.