h1

Floating divs and odd behaviour

March 20, 2009

I came across an unexpected problem in class this week. We were producing two-column floating layouts in the internet 1 class. You know the sort of thing 760 px, full width header, nav and body side by side and a full width footer. Someone asked me how to add a block underneath the nav column so that the background didn’t show through when the nav and the body were different heights. “No problem”, I said, “Just add an container div around the nav and body blocks and everything will be fine.”

Not so! If you try this kind of layout in IE it works as you would expect and you get:

correct

This is what I confidently expected to see in Firefox too but no, what firefox gives you is:

problem

I could not understand what was happening. Dreamweaver agreed with Firefox and didn’t show my container div either. I did one of my usual tricks and wrapped a big ugly border around the missing container:

redline

The thick red line shows where the container is. As you can see it appears underneath the two floating panels as though there is no content. I was stumped in class and had to leave it – others were waiting. Afterwards though I did some googling and found the answer:

Clearing a float container without source markup [positioniseverything.net]

It turns out that because my container only contains floating content, which are not counted as being part of the document flow the layout engine treats it as being empty. It is possible to put an empty paragraph at the bottom with a clear=both property to force some content below the panels, but this would be ugly.

The link above gives a nice CSS based fix using the :after pseudoclass (which I had never heard of either). Creating a class in the stylesheet:

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

Essentially this creates some content after the block. The content is a single . made invisible with zero height. Crucially it is able to set clear:both to force it to appear under the boxes.

This does the job nicely. The original article explains more fully and includes further detail about running in older browsers like IE5.5 on the Mac. I can’t quite see why I’ve never come across this before. Perhaps I always threw my container around the header and footer too. It is nice to fix this though.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.