Tutorial Force Element To Self-Clear its Children

by in , 0

A.K.A The "Clearfix" hack.

.clearfix:after {
     visibility: hidden;
     display: block;
     font-size: 0;
     content: " ";
     clear: both;
     height: 0;
     }
.clearfix { display: inline-block; }
/* start commented backslash hack \*/
* html .clearfix { height: 1%; }
.clearfix { display: block; }
/* close commented backslash hack */

Just apply a class="clearfix" to the parent element. This is an improved version of the original, and documented here.

Updated by Jeff Starr to be cleaner, based on the fact that nobody uses IE for Mac, which is what the backslash hack was all about.

.clearfix:after {
	visibility: hidden;
	display: block;
	font-size: 0;
	content: " ";
	clear: both;
	height: 0;
	}
* html .clearfix             { zoom: 1; } /* IE6 */
*:first-child+html .clearfix { zoom: 1; } /* IE7 */

Updated again... "group" class name is nicer and more semantic (via Dan Cederholm). Content property doesn't even need the space, can be empty string (via Nicolas Gallagher). Without any text, font-size is un-needed (Chris Coyier).

.group:after {
	visibility: hidden;
	display: block;
	content: "";
	clear: both;
	height: 0;
	}
* html .group             { zoom: 1; } /* IE6 */
*:first-child+html .group { zoom: 1; } /* IE7 */

Of course if you drop IE 6 or 7 support, remove the associated lines.

Update May 18, 2011: Nicolas Gallagher again with the "micro" clearfix. Also see this additional stuff.
.group:before,
.group:after {
    content: "";
    display: table;
} 
.group:after {
    clear: both;
}
.group {
    zoom: 1; /* For IE 6/7 (trigger hasLayout) */
}

Update August 2012: I'd say for the most part these days (if you only need IE 8 and up) this is fine:

.group:after {
  content: "";
  display: table;
  clear: both;
}

Leave a Reply