There are still a lot of <div class="clearfix"></div> elements scattered throughout code on the Web, and, 90% of the time, they're not necessary.

I've been able to pull off some of our trickiest designs in the last year without having to yield to the clearfix hack even once, thanks to one simple but under-discussed trick -- CSS overflow: hidden.

A quick example. Suppose we have the following code:

<style>
    #outer {
        border: #000000 2px solid;
        background: #eeffee;
    }

    #inner-1 {
        float: left;
        width: 200px;
        height: 100px;
        border: #0000ff 2px solid;
        background: #eeeeee;
    }

    #inner-2 {
        float: right;
        width: 200px;
        height: 100px;
        border: #ff0000 2px solid;
        background: #eeeeee;
    }
</style>

<div id="outer">
    <div id="inner-1">
        Box 1
    </div>
    <div id="inner-2">
        Box 2
    </div>
</div>

Rendered, the above will look like this:

Box 1
Box 2

The inner divs float into the same context as the outer div, causing the outer div to collapse around them instead of containing them. Now, rather than adding unnecessary markup, we can rectify our css for the outer div to look like this:

...
    #outer {
        border: #000000 2px solid;
        background: #eeffee;
        overflow: hidden;
    }
...

Voila! Here is the effect:

Box 1
Box 2

Adding overflow: hidden to the outer div established a new context for its contents, which means a floated child div will be contained within its parent. As long as the outer div has no height set, overflow: hidden works great, but any overflow value other than visible will have the same effect.

And, don't worry, this is completely standards-compliant CSS2.

Comments