Breaking Floats Without Hacks

Learn how to properly use the CSS float and the clear properties.

Using the CSS Float and Clear Properties

I have run across so many problems with designers confused about how to properly make use of the CSS property, clear. As a result, I'll be discussing two common mistakes and how to avoid them in this article.

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 just won't cut it 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. Natually, 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. }

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.

Navigation

Web Design Resources and Articles