CSS-Tricks PSD to HTML

The How and Why of Clearing Floats

You’ve heard of “clearing floats”, but do you really understand it? The whole problem is that floated objects do not add to the height of the object the reside in properly. As you can see below, these divs with the class “floated_box” are within the div “main_container”, yet on the page they are outside that container div.

#main_container {
 width: 400px;
 margin: 20px auto;
 border: 2px solid #cccccc;
 padding: 5px;
}

.floated_box {
 float: left;
 width: 100px;
 height: 100px;
 border: 1px solid #990000;
 margin: 10px;
}
<div id="main_container">
 <p>Some content.&lt;/p>
 <div class="floated_box"></div>
 <div class="floated_box"></div>
 <div class="floated_box"></div>
 <div class="floated_box"></div>
 <div class="floated_box"></div>
</div>

float1.png

All we need to do is clear the float, and this entire problem goes away. Put this empty div AFTER your last floated object:

<div style="clear: both;"></div>

And you get this:
float2.png

This fix does add some useless markup, which is antithetical to the tao of CSS, but it’s an easy cross-browser fix that won’t let you down.


Theoretically Related Articles:


Responses


  1. 1

    Gravatar

    There is a better way than using a non-semantic empty div element for clearing floats, several in fact, but I’ll list the simplest one. I use a line break to clear floats.

    .brclear {
    clear:both;
    height:0;
    margin:0;
    font-size: 1px;
    line-height: 0;
    }

    In the html it them becomes
    It takes up no space and is preferable to using an empty div.


    Comment by LadynRed — August 15, 2007 @ 6:25 am

  2. 2

    Gravatar

    I see what you mean, but I think it’s a horse apiece. One useless HTML element is the same as another if you ask me, and this way doesn’t clutter the CSS.


    Comment by chriscoyier — August 15, 2007 @ 7:24 am

  3. 3

    Gravatar

    #main_container {overflow: auto}

    that should do it with no additional markup needed.


    Comment by David Kypuros — August 15, 2007 @ 8:15 am

  4. 4

    Gravatar

    #main_container {overflow: auto} fixed my problem without adding any other div! Thanks!!!!


    Comment by Cath — May 28, 2008 @ 9:03 am


Leave a comment

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

Live Comment Preview


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