CSS floating and clearing
Recently I ran into a problem and found myself a bit perplexed. I was working on a flexible layout when I ran into an issue with clearing floats. Let me describe the scenario:
It’s a two-column layout with a right-floated column followed by a left column with a flexible width. It looks somewhat like this:
<div id="right-col">
Content...
</div>
<div id="left-col">
Content...
</div>
with this CSS code:
div#right-col{
float: right;
width: 150px;
}
div#left-col{
margin: 0 170px 0 10px;
}
This means that the left column will have a width that’s expanding within its current given area, but that it always has a right margin not to interfere with the right column. So far, so good. But then I started to add floated elements in the left column and then clearing them, I also cleared the floating of the right column.
I guess this is correct behavior since there was no floated container in between, but still tricky, because I had to use floated elements there. After some discussions with Faruk, he gave me the suggestion to use an inner floated container in the left column, thus making sure to achieve just a “local” clearing. So, the new HTML became this:
<div id="right-col">
Content...
</div>
<div id="left-col">
<div id="left-inner-col">
Content...
</div>
</div>
with this CSS rule added:
div#left-inner-col{
float: left;
width: 100%;
}
Works like a charm!
Moral of the story: if you clear floating, make sure you know in what context you do it.
















