The How and Why of Clearing Floats

Posted on: 8/9/2007   By: Chris Coyier 5 Comments

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.

Responses

  1. LadynRed says:

    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.

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

  3. #main_container {overflow: auto}

    that should do it with no additional markup needed.

  4. Cath says:

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

  5. Nicolaj says:

    I use {overflow: auto;} all the time for this. Any reason why I should use divs to clear instead? Overflow does seem a bit hack’ey to me, but then again so does clearing divs…

This comment thread is closed. If you have important information to share, you can always contact me.