CSS – Clearing Floats

A common problem with float-based layouts is that the floats’ container doesn’t want to stretch up to accommodate the floats. If you want to add, say, a border around all floats (ie. a border around the container) you’ll have to command the browsers somehow to stretch up the container all the way.

Clearing Floats

Floated items can be taller than non-floated content

Snagit Capture

Clearing is necessary if all children are floating

Common float-clearing methods:

  1. Clear with a subsequent element
  2. Manual clearing
  3. The clearfix
clear: left / right / both
Clear with a subsequent element

HTML

<div>
	<img src="ski.jpg" alt="Skiing!" />
	<p>To successfully ski, simply do not fall.</p>
</div>
<div class="intro">
	<p>Whee!</p>
</div>

CSS

img {
	float: left;
}
.intro {
	clear: both;
}
Clear with a subsequent element

This requires sequence to stay intact – breaks if things move.

Background / border do not extend.

Snagit Capture

Manual clearing

This requires an empty element

HTML

<div>
	<img src="ski.jpg" alt="Skiing!" />
	<p>To successfully ski, simply do not fall.</p>
<div class="clear"></div>
</div>

CSS

.clear {
	clear: both;
}
The clearfix

The clearfix was originally developed by Tony Aslett, and then refined by Nicholas Gallagher.

When used on the parent, the children will be self-cleared.

HTML

<div class="group">
	<img src="ski.jpg" alt="Skiing!" />
	<p>To successfully ski, simply do not fall.</p>
</div>

CSS

.group:before,
.group:after {
	content: "";
	display: table;
}
.group:after {
	clear: both;
}
.group {
	zoom: 1; /* IE6&7 */
}

Be first to comment

Leave a Reply