Sep 21

elegant fix for heightless container div that has only floated elements in it

Mon, 09/21/2009 - 11:46 — peter

The Problem

if a container div only contains floated divs, that container div has no height. the usual fix is to add an extra markup on the code with a clear: both (or left/right) style. but that is putting layout on the markup, which makes you go to css hell without 72 div virgins waiting for you.

The Solution

how to fix it? simple meyer fix I learned on the NAGW 2009 Conference: put overflow: hidden (or auto) on the container div.

see this in action. let's get an unsuspecting page whose container div has no height.

fire up firebug and go to the #footer div. you can click on it on the code, but nothing is highlighted cuz all of its inner divs are floated.

now, go in and add an overflow declaration to that #footer div. see what happens now on firefox when you click on the #footer code? it highlights it because it now has a height. no extra markup necessary.

Easy Peasy!
-PCP