1. Technology

Understanding the CSS Clear Property

The CSS Clear Property for Clearing Floated Elements

By

The clear CSS property has been part of CSS since CSS1. It lets you specify what elements can float beside the cleared element and on which side(s). The clear property has five possible values:

  • none
  • left
  • right
  • both
  • inherit

How to Use the CSS clear Property

The most common way to use the clear property is after you've used a float property on an element. For example:

<img src="image.gif" alt="my image" style="float:left;">
<p>Text next to my image.</p>
<p style="clear:left;">Text that is below my image.</p>

All elements default to clear:none;, so if you don't want other elements to float beside something, you must change the clear style.

When you are clearing floats, you match your clear to your float. So if you floated the element to the left, then you should clear to the left. Your floated element will continue to float, but the cleared element and everything after it will appear below it on the web page.

If you have elements that are floated to both the right and left, you can clear just one side or you can clear both.

Using clear in Layouts

The most common way most designers use the clear property is in layout of page elements. You might have an image floating inside a block of text and want the next paragraph to start below the image, or you might have an entire column of text that you want to float beside another bunch of text, with some text appearing below.

Here is the HTML for a layout in this form. It has one div container holding another that is floated to the left.

<div style="background-color:#ccc; width:100%;">
  <div style="background-color:#c00; color:#fff; width:25%;float:left;">
    <p>A short floated div</p>
  </div>
  <p>Contents inside the container div that are going to be to the right of the floated div.</p>
</div>

This will work fine, with the shorter div floating to the left of the rest of the contents of the main div. As you can see in this example.

You can clear the text next to the floated box by simply adding a <br style="clear:left;"/> tag where you want it to start writing under the floated box. For example.

But the problem comes when the floated box is longer than the contents next to it. Then, as you can see, the background color of the main box is not carried down to the bottom of the floated box.

Luckily, there is an easy way to fix this: the overflow property. By setting the main box to overflow:auto; the background color will remain beside the longer floated box to the very bottom. As in this example.

©2014 About.com. All rights reserved.