CSS: how the clear property works

The CSS clear property works on elements that come near or after a floated element. Since a floated element affects the computation of horizontal space of a web document, this property re-establishes the normal flow of a layout. In fact, when an element is floated, all elements near it surround that element by placing themselves to its right or left outer edge.

For example, if an element is left-floated, all subsequent elements will be shifted to its right edge, while if an element is right-floated, all subsequent elements will be pushed to its left edge. Using Firefox's terminology, this is called float damage and it occurs when the computation of space is rearranged due to float action.

Of course web developers wished to have more control over this behavior. For that reason, the clear property was introduced in CSS 2 (back in 1998). This property performs a simple task: it puts back in the normal flow an element that comes near or after a floated element. For example, if you have a left-floated image and a paragraph that contains it, to clear the next sibling paragraph you can write:

p:first-child + p {
  clear: left;
}

By doing so, the sibling paragraph stops surrounding the floated image and it's displayed just under the first one. Curiously, this property can also be applied to float themselves. In that case, if you have more than one float on a line, this declaration prevents other floats from being displayed near the first one.

However, this property can actually cause some problems when it comes to vertical margins. For example:

p:first-child + p {
  clear: left;
  margin: 0.5em 0;
}

Browsers like Firefox, Safari, Opera, Chrome and IE8+ correctly calculates the amount of vertical space for the cleared element, while IE7 (and lower) add some extra space. You should always be aware of this fact when dealing with clearing and vertical margins.

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.