Clearfix Method

The eternal question for beginning web designers often is, “How do I get my background image/color to fill all the way down the page when I float two divs next to each other?”

Enter “clearfix.”

I first learned about the clearfix method by reading the book “Stylin’ with CSS: A Designer’s Guide” (1st Edition) by Charles Wyke-Smith, now in its 2nd edition (See it on Amazon).

When you float two items next to each other (say a nav bar and a content area) the two divs collapse in height because floated elements have no height. Say you then try to set a background to the div containing both your nav bar and content area. What happens? A whole lot of nothing. Why? Because the containing div is wrapping two divs that have no height themselves, so what makes you think your container div is going to have a height?

To fix this problem simply put the class of “clearfix” on the containing div and copy and paste the following into your CSS file.

/* CLEARFIX CONTROLS --------------------------------------------------- */
.clearfix:after {content:"."; display:block; height:0; clear:both; visibility:hidden;}
.clearfix {display: inline-block;} /* a fix for IE Mac */
/* next a fix for the dreaded Guillotine bug in IE6 */
/* Hides from IE-mac \*/
* html .clearfix {height: 1%;}
.clearfix {display: block;}
/* End hide from IE-mac */
/* end of "no-extra-markup" clearing method */

Now I believe I have seen some Javascript fixes out there as well but why get involved with scripts when this is just as easy, if not easier? Besides, in my opinion, if you can do it elegantly with CSS you should really stay away from another Javascript call on your page.

This entry was posted in CSS, Code Samples and tagged , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>