Clearing Floats the Easy Way

If you, like me, have spent any time devising CSS based layouts then you’ll no doubt have run into this issue. Here’s how I deal with it and some further reading on the subject.

Floated elements are removed from the document flow, and other elements flow around them. This is great, and very useful but the catch is that removing an element from the document flow means that as far as its parent is concerned it no longer has height. So if the tallest element in your layout is, or might at any time be, floated you’ve got a problem.

So we need a way to prop the parent open. Any designer worth his salt will likely figure out this first, ugly method and immediately be ashamed. I know, because not so long ago I found myself in this very position and this is what I did.

<div>
    <div style="float:left;">Floated Content</div>
</div>

I know. Shameful. But there’s a better way. In fact there may be yet an even better way in certain cases, but I’m going to focus on the way that I’ve been employing to great success.

It should be noted that I did not come up with this technique. It was created by Tony Aslett, of csscreator.com and found its way to me via Position is Everything. I fully recommend reading the PiE article as I’m not going to delve into the specifics.

So here’s the CSS I use

.clear:after {
    content: ".";
    display: block;
    height: 0;
    clear: both;
    visibility: hidden;
}

And the modified markup

<div class="clear">
    <div style="float:left;">Floated Content</div>
</div>

Ta da! Look at that pristine markup. Again, if you want to know how and why this works read the PiE article, or if you don’t care just use it and be glad.

PS – In addition to self-clearing floats I find this technique very useful for ensuring that absolutely positioned elements with scrolling content don’t lose their bottom padding (which drove me nuts for a while).


About this entry