www.1-4-you.net


Clear


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

Lets try it. This is the CSS well use throughout the page:

We want the black border to go around both our floating columns. That doesnt happen, though. The container div itself has no height, since it only contains floating elements. Therefore the border stubbornly stays at the top of the floating columns.

The old solution to this problem required you to add an extra element with clear: both to the container. Once it was in place the container contained a non-floating element, which means it stretches itself up to accomodate it:

This can be done either by adding the extra element in the HTML source code (as the example above does) or by using the :after pseudo-class to generate it. Since Explorer (Win and Mac) doesnt support :after this second solution was mainly of theoretical interest.

In any case, adding an HTML element for presentations sake is something weve learned to avoid. Unfortunately the problem could not be solved in any other way, until now.

It was Alex Walker who first posted a new, simpler solution, though he gives the credits for actually inventing it to Paul OBrien. In any case, the solution seems to be:

The use of a width or height declaration is required to make the effect work in Explorer Windows and Opera. If you dont include it Explorer Windows continues to show the border at the top of the columns, as if there were no overflow. Opera completely hides the content of the container.

A width: 100% is a neat starting point, although more complicated layouts may require other values.

As Dave Shea noted, this solution might cause unwanted scrollbars if the content escapes from the container box. Personally I wonder if this will be a serious problem. overflow: hidden makes sure that no scrollbars will ever be visible. Of course some content might be hidden instead, but if we make very sure that

On the other hand, never say never. In pure tests like the ones above the effect works fine. In real-world sites, where theres plenty more CSS to confuse browsers, something will eventually go wrong somewhere. Until we reach that point, though, this technique will do nicely.