How To: Clear Floats in CSS

Have you ever had the situation where you tried to clear a floating element in your web design only to have something not line up right? Maybe the box model in your design didn't line up right. Maybe a column was too long and ran over something it shouldn't. You look at your CSS and see clear: both; in the right place and can't find the problem. There are better ways to clear floats. They deal with cross browser issues and do so without adding extra elements to a page.

A common way to fix the float problem is to stick <br style="clear:both"/> after your floated items to clear the float. This works and it keeps columns aligned. But, it adds extra elements to the page and you may have spacing issues from this tag.

Instead of doing this I'd suggest two different methods.

Position Everything Method

Over at position everything there is an article on how to clear floats without adding any structured markup to a page. To do this you first add the following to your css:

.clear-block:after {
  content: ".";
  display: block;
  height: 0;
  clear: both;
  visibility: hidden;
}

.clear-block {
  display: inline-block;
}

/* Hides from IE-mac \*/
* html .clear-block {
  height: 1%;
}
.clear-block {
  display: block;
}
/* End hide from IE-mac */

Then, in your page have something like the following:

<div id="wrapper" class="clear-block">
  <div style="float:right">
    // Your content here
  </div>
  <div style="float:left">
    // More content here
  </div>
</div>

This is the method built into drupal and one that works well. It takes advantage of the rarely used :after method in css. It, also, works in all the major browsers including the now dead IE for Mac.

Paul O’Brien Method

Paul O'Brien suggested adding overflow:auto to the outer div.

An example of this would look like:

<div id="outer" style="overflow: auto;">
  <div style="float:right">
    // Your content here
  </div>
  <div style="float:left">
    // More content here
  </div>
</div>
<div id="footer" style="clear:both;">
  // Some footer content
</div>

Adding overflow:auto seems to be a gentle enough reminder to browsers that the content in them is in them and to enclose the whole thing in them.

While, I used the CSS in style tags here I'd suggest putting all the CSS in style sheets in a production site. Happy Positioning.

Thanks

These were both great tips. I have been looking for some other ways of clearing elements without using divs as the clearing elements.