How to clear floats for proper footer placement
Most novice CSS users have never even heard of the “clear” property. I know in the past, I hadn’t, and racked my brain for hours trying to get my layout to display correctly with a floating sidebar. Here’s how it works:
When rendering divs, the browsers normal flow is to place one, then afterwards in the normal flow of things, place the next one. When you want to have divs side by side, the usual solution is to add the “float” property to them. In the case below, both the “left-nav” div and the “content” div have the property “float:left;”. We can then put content inside the floated divs, and have a happy layout. The problem is, there is nothing in the normal flow of things to continue the layout, so we need to tell the browser to push things down. Note these two examples:
Incorrect:
<div id="wrapper">
<div id="left-nav">
....
</div>
<div id="content">
....
</div>
</div>
<div id = "footer"><p>All of this text is hidden underneath the floated divs!!</div>
Correct:
<div id="wrapper">
<div id="left-nav">
....
</div>
<div id="content">
....
</div>
<div style="clear: both;"><!-- clear floats --></div> </div> <div id = "footer"><p>My footer now displays below the floated elements!!</div>
That one little line tells the browser to “keep going”, and moves the flow down. The easiest way to test this is to give “wrapper” a background color, and look at the difference in the two code pieces when there is content in each element.
HIGH TECH WEB 2.0 INTERACTIVE EXAMPLES:
Example 1 (Incorrect):
+--(#wrapper)---------------------------------+
| +-----------+ +--------------------+ |
+---| |----| |---+
| | | |
| | | |
| | | |
| | | |
| #left-nav | | #content |
| | | |
| | | |
| | | |
| | | |
| | | |
| | | |
+-----------+ +--------------------+
Example 2 (Correct):
+--(#wrapper)---------------------------------+ | +-----------+ +--------------------+ | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | #left-nav | | #content | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | +-----------+ +--------------------+ | | | | +---clear: both-----------------------+ | | | +---------------------------------------------+
| 2.9 |
Stumble it!
Post Info
This entry was posted on Monday, December 31st, 2007 and is filed under css, design. It has 195 viewsComments Feed. | Leave Comment | Leave Trackback.
Previous Post: Add Google Analytics code to your entire website in a flash »
Next Post: AJAX Contact form »
























