Clearing Floats without Extra Markup
I’m sure you’ve done it. Every designer has. You cleverly assign a background image to a page division (DIV) that contains some more DIV elements you’re going to float right and left to make columns. You float the columns right and left. “Voila”, you say.
Then, you look closer. Your background that was supposed to appear between and around the columns to unify the design has simply disappeared. Where did it go?
As far as I know, Internet Explorer and Opera are the only browsers in which a parent DIV expands to contain floated child DIVs (the columns in our example). What do we do for Firefox, Safari, and others?
A simple hack I’ve used very often comes from the kind folks at Position Is Everything. I’ve copied it below:
.clearfix:after {
content: ".";
display: block;
height: 0;
clear: both;
visibility: hidden;
}
All you need to do is to assign a class of “.clearfix” to the element that is being floated and is protruding below its parent. If you’d rather not add ANY extra markup to your HTML, you can just refer specifically to the elements that need clearing without adding the class.
If you have any questions or comments, please share them below. Also, visit the very helpful page at Position Is Everything for more details. They’ve also linked to an updated method as covered by SitePoint.
Add comment July 16th, 2008