Each of the examples below have a red floating block within a parent element which has a bright green background. The first example, you should note, does not reveal the bright green background of the parent. In its case, the floating element is its only content, and it has not been "contained."
To understand why, you must understand what floating an element actually does to its behavior. Per the spec, a floated element is removed from the ordinary document flow. This means that a parent will not respond to its height. Elements that appear AFTER the floated element respond by moving its inline elements (like text) around the floated element. You'll note that in example two, the text starts next to the floated element. With the proper amount of content, it will also wrap under the floated element. Notice that the parent, in the second example, respond only to the height of the non-floated element.
Additionally, subsequent elements can get around a floated element by applying the clear property. Clear is float's kryptonite. Clearing will start the content below all floated elements. The third example shows how an element with the clear property makes the container respond.
Knowing both how non-floated content behaves AND how clearing works, we can create a good solution for the containing floats issue.
The example source is at the bottom. The lines that make this work are emphasized.
This content is AFTER the floated content, and the parent only "contains" me, not the red box.
This is a special clearing element
Note: for the purposes of the following CSS, the last example uses the class called "clearing" on the parent element.
div {
background-color: #0f0;
}
/* used in the 3rd example as the "special"
clearing block */
p.clear { clear: both; }
div.float {
background-color: #f00;
padding: 5em;
float: left;
}
/* CLEARING TRICK */
/* IE doesn't understand this:
creates an artificial clearing block
for good browsers */
div.clearing:after{
content: ".";
display: block;
height: 0;
clear: both;
visibility:hidden;
}
/* IE will contain floats incorrectly when given
some height -- also since, IE treats height as
min-height, it doesn't hurt the height */
* html div.clearing { height: 0; }
By far, this is the simplest containing trick:
/* some width is required */
.clearingContainer { width: 100%; overflow: auto; }
That's it. After applying the overflow: auto; property/value to the container, most browsers contain the float automagically (one notable exception is Opera 7.x). See for yourself:
Credit, where credit's due on this one: Thanks paul.