Welcome to Code Couch

How to use “clearfix” CSS to clear floats without markup

Posted by at 10:43pm on October 14, 2008.

When an element is floated, it is taken out of the normal flow of the document. As a result, the element takes up no height (in the normal flow) – and any wrapping parent element will not automatically resize to accommodate the height of the floated element. Here is some sample HTML that shows this in it’s simple form:

...
<div id="parent" style="background-color:#F00;">
	<div id="child" style="float: left;">Floated element</div>
</div>
...

Given the child element is floated, it doesn’t affect the height of the parent element – and so the parent element remains with no height (and the red background colour is never shown).

The W3 describe floating an element and the use of a “clearing element” (a block level element with the clear CSS property set). This is not acceptable for all layouts. It would be nicer if all this could be carried out using CSS – providing a separation of content and layout into the bargain.

Rather than attempt to merely re-word much of what is already online, you can read about how the CSS for this works in more detail at Position is Everything. Whilst their implementation is slightly different to the one presented below, their description is excellent (and they are credited with bringing together all the threads to make this solution usable).

The clearfix solution below is our current “best practise” effort to date. We have switched from using the typical “.” to using a space ” ” in the content rule due to reports of some layout issues in Firefox.

<style type="text/css">
.clearfix:after {
	clear: both;
	display: block;
	content: " ";
	height: 0px;
	visibility: hidden;
}
.clearfix {
	display: inline-block;
}
/* Hide these rules from IE-mac \*/
* html .clearfix {
	height: 1%;
}
.clearfix {
	display: block;
}
li.clearfix {
	display: list-item;
}
/* End hide from IE-mac */
</style>

We extended the normal rules to include setting the correct display (list-item) for use on list items (as a direct result of some problems with floated lists). If you don’t care about IE-mac support (don’t forget that Microsoft finally retired IE 5 for the Mac) then you can avoid using the “commented backslash hack” all together.

Going back to our original HTML code, we can place the clearfix class on the parent element to ensure that it inherits the height of it’s floating child elements (and the red background will now show):

...
<div class="clearfix" id="parent" style="background-color:#F00;">
	<div id="child" style="float: left;">Floated element</div>
</div>
...

You can read more about the clearfix solution all over the place, including:

Post to Twitter

Tags: , ,

Comments

There are no responses to this post.

Leave a reply

Comments are closed for this post.