Update: A more comprehensive article on floats is now out: All About 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.</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>
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:
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.
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.
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.
#main_container {overflow: auto}
that should do it with no additional markup needed.
#main_container {overflow: auto} fixed my problem without adding any other div! Thanks!!!!
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…
The Problem with overflow auto:
Work great when you load the page. But when you resize the page, or you add additional content to the containing elements using ajax, then the auto does not accommodate the additional height. In this scenario you get a scroll bar appearing withing the element where you assigned the :auto overflow property.
I am currently looking for a solution to this.
I tried using the #container{overflow:auto;} but it gave me a horizontal scroll bar in my container instead. Clear div doesn’t. Granted my css is a bit of a mess right now, but I’m trying to get the hang of it.
There is no “why” in this article.
I am now searching for alternative articles to actually find out WHY this is working.
Maybe you should finish the article to explain the “why” part?
There is more information here: https://css-tricks.com/all-about-floats/
Thanks Chris!