Clearing Floats: The FnE Method
When it comes to laying out pages in CSS/XHTML, I have always leaned towards the
float method rather than
position. But there’s always that issue of clearing your floats. It wasn’t until recently I discovered a little trick to avoid extraneous markup for the sole purpose of clearing floated elements. I call it the Float (Nearly) Everything Method.
Below is an example of a floated
div inside another
div, the floated element containing more content than its parent.
Note: I am using inline styles for this example, so feel free to peek under the hood to see what’s going on.
What you will see in most browsers (save IE) is the content in the child
div flows over the parent. But watch what happens when I add a simple
float declaration to the parent
Magic. The floated parent
div expands to enclose the floated child
The result of this, however, is that the ‘grandparent’ element of the nested div will not expand to enclose the parent element, unless it too is floated, or there is another element beneath it given a
clear declaration. Hence the naming of this method, Float (Nearly) Everything.
In almost all my pages I use a
div#wrapper to encase all the content. Many times this is centered, so floating that element is out of the question. However, anything inside it is usually fair game, unless I know there aren’t going to be any floated elements inside it. Typically, the only place I usually don’t have floats is in the footer of the document. So, I can simply add
clear:both; to the
float everything else inside the
View the Demo
So there it is. Clearing floats with no extra markup in the XHTML document. Sure, it takes a little more tweaking, and maybe a few CSS hacks, but at least all the presentation data is left in the CSS file, and no
<br class="clear" /> in sight.