CSS Clearing in Nested Containers

by Jim Feb 13, 2010 1:48 PM

floats

As I’m working on the layout for this blog, I ran into this issue with clearing of DIVs in nested containers. The lower example shows that the clear:both in the child container actually clears the left-floated menu in the parent – I only wanted to clear the floated DIVs in the child, as pictured at top.

The rule here is that that clear applies to the nearest floated parent. So in the top example, clear applies within the right-floated child. If you want a region on your page to have predictable floating, it should itself be floated.

This is an important design rule for blog templates, as CSS-savvy users (like myself) are likely to use floated elements, and possibly clearing, in their posts.

The problem that I have with the upper layout is this: As the browser loads the page, it doesn’t know that the main container is going to extend below the left and right columns, until the footer loads. Until then, the container has zero height. Therefore, it doesn’t render the background color of that main container behind the columns; it shows the page background instead. Only when the footer loads, does the main container extend to its proper height and show its background over the page background. This can lead to annoying flashing of background colors as the page loads and renders.

Update:

I found a solution to the render/flashing problem here. Basically, we use CSS to append a clearing element to the container; since this applies when the container is created, it will expand with its floated contents immediately, rather than staying collapsed until the footer loads. The CSS looks like this:

/* clearfix magic */
/* to prevent background color from showing behind post during rendering */
div.clearfix:after {
content: ".";
display: block;
clear: both;
visibility: hidden;
line-height: 0;
height: 0;
background-color: #454545;
}

div.clearfix {
display: inline-block;
}

html[xmlns] .clearfix {
display: block;
}

Tags:

Code

Add comment


(Shows Gravatar icon; will not be displayed)

  Country flag
Click to change captcha
biuquote
  • Comment
  • Preview
Loading