Clear as mud

Sometimes, clearing isn’t as obvious as you might think.

We’ve previously explored the ‘margin under float’, and ‘same side float’ / ‘opposing floats’ techniques, both of which can be used to achieve a basic 2-column layout. However, there’s an issue with the former which needs careful attention.

In this example, we have a floated sidebar, with a left-margined content area. Within the content, we have two opposing floats followed by a paragraph. To prevent the floats running into the paragraph, we add a clearing element between them:

.sidebar {
    float: left;
    width: 7em; }
.content {
    margin-left: 8.5em; }
float: left
float: right

A simple paragraph

Note, however, that the effect of ‘clear’ on this element is to clear not just the opposing floats within the content area, but also the floated sidebar. As a result, our paragraph is pushed down and an undesired amount of whitespace presented between it and the opposing floats.

Using the same side floats technique to control the overall layout of content and sidebar solves the problem:

.sidebar {
    float: left;
    width: 7em;
    margin-right: 1em; }
.content {
    float: left; }
float: left
float: right

A simple paragraph

The reasons behind this are slightly obscure; to understand them, you need to know about block formatting. Essentially, the first method does not create a separate ‘block formatting context’, so the clear applies to all three floats. Floating the content block, as in the second method, creates a new block formatting context which limits the clear to only those floats within the content.

Internet Explorer

Of course, the IE story is an altogether different one: surprise, surprise. If you’re viewing in IE (7.0 or lower), you should see the same rendering for both examples. Looks like IE doesn’t even understand block formatting contexts, which is:

Although I’ve never personally come across the details of block formatting contexts before, I certainly have now, and I’m sure that knowledge will be useful in some future layout troubleshooting. However, I have a nagging feeling that some day I’m going to need the ‘separate contexts’ behaviour, and I really don’t know what the IE workaround will be for this.


Comments

Leave a comment