Breaking Floats Without Hacks

Learn ways to use the CSS float and the clear properties if you have a page that's being difficult.

October 15, 2006

Using the CSS Float and Clear Properties

I have been questioned by so many web designers who are confused about how to work with CSS floats and making use of the CSS property, clear. As a result, I'll be discussing two common issues and how to get around them in this article.

2014 Update

Thankfully the days of Internet Explorer 6 are finally gone and these extra properties needed to get floats cleared properly are no longer needed!

Cancelling Inherited Floats

While float: none; can work, clear can be an easier solution.

  1. #nav li {
  2.     width: 140px;
  3.     float: left;
  4. }
  5. #nav li li {
  6.     float: none; /* You can use the below instead! */
  7.     clear: left;
  8. }

Floats and clear are two of the most important CSS properties, so hopefully, whether you're an amateur or expert, this article gives you something to think about.

The Full Break

When you want to clear all floats across the entire width of the page or a div, this single line of CSS code sometimes just won't cut it in older browsers or on complicated layouts when using: <div class="clear"></div>.

  1. clear: both;

Instead, we're going to use four lines.

  1. width: 100%;
  2. height: 1px;
  3. margin: 0 0 -1px;
  4. clear: both;

Alright, let's break this down. First of all, the major problem with clearing correctly in all browsers lies mainly in a few of Internet Explorer's quirks. Both width: 100%; and height: 1px; force the browser into accepting that there is a div there. The margin: 0 0 -1px; negates the 1 pixel space that height introduced; this is the only property that is not required. Naturally, clear: both; is the special ingredient to make all of this work.

I've seen this hack around, but if anyone can find an instance where the following code works properly and mine doesn't, please email me, I'd love to see it!

  1. .clear {
  2.     width: 100%;
  3.     clear: both !important;
  4.     display: inline-block;
  5. }
  6. .clear:after {
  7.     content: ".";
  8.     display: block;
  9.     height: 0;
  10.     clear: both;
  11.     visibility: hidden;
  12. }
  13. * html .clear {
  14.     height: 1%;
  15. }

Web Design Resources and Articles