The Hidden Overflow Technique

Let's talk about floated elements. Yeah, those elements that need to be positioned to the left or right of other elements. You've floated your menu to the left? Well done. That's a pretty good place for your menu.

But hold on, when your content is shorter than your menu, the menu floats to the side of the footer as well and putting a div around it will only make the menu float over the top of the footer. That's not cool. Most developers run into this problem (or worse, floats can get weird) and have learned about clears. Clears are simple, generally you'd have your HTML like this:

<div id="header">
Header Stuff
</div>
<div id="menu">
Menu Stuff
</div>
<div id="content">
Content Stuff
</div>
<div class="clear"></div>
<div id="footer">
Footer Stuff
</div>

And your CSS would look something like:

#menu
{
float: left;
width: 100px;
}

.clear
{
clear: both;
}

Essentially, this stops the float from interfering with anything after the clear. So it will float to the left of the content, but not to the left of the footer. This is great, it solves all kinds of problems which float creates. Unfortunately, every now and then you'll run into problems which involve multiple floats and clears. Sometimes, a clear inside a float will clear everything to below an element outside the float. This is where the title of this article comes in handy.

The hidden overflow technique. This works in a slightly different way from the clear system. Here's the HTML:

<div id="header">
Header Stuff
</div>
<div id="middle">
<div id="menu">
Menu Stuff
</div>
<div id="content">
Content Stuff
</div>
</div>
<div id="footer">
Footer Stuff
</div>

And the CSS:

#middle
{
overflow: hidden;
}

#menu
{
float: left;
width: 100px;
}

The way this works is surrounding you floating items with a div, then applying a hidden overflow to that div. Usually overflow: hidden would hide anything that's larger than the width or height of the element. However, since we haven't applied a height and the width is already 100%, it won't have a noticeable effect to the overflow. Instead, it will make the contained items do their floating thing inside the div, well making the entire div act like part of the page.

 
21/12/2009