Pew Pew Laser Blog

Code. Glass art. Games. Baking. Cats. From Seattle, Washington and various sundry satellite locations.

Pew Pew Laser Blog Archives — by Blog ID

Clearfix (with an IE7 solution).


If you begin working with CSS for your web page layouts instead of tables (and you really should), you will encounter problems with floated elements. The most mind blowing issue is when you have an element floated to the left or right, but that floating element escapes OUT of the element that contains it. This behavior is, in fact correct, since a floated element is removed from the normal flow of the document, and hence, any elements containing it. However it really can play hell with your web pages - so here's my preferred solution.

Very Tall Image This paragraph, with a white border contains a very tall image that is floated to the right of the paragraph, while text flows around on the left side. However, you can see here that the image very rudely busts out of the paragraph element.

There are a variety of ways to correct this, but the most robust method I've found is using Clearfix by PositionIsEverything. First, add a clearfix class to your main stylesheet with the following style declarations.

 {	content: ".";
	display: block;
	height: 0;
	clear: both;
	visibility: hidden;

Then assign the clearfix class to each element from which floated items are escaping. Here's the code for the corrected paragraph:

<p class="clearfix">

Very Tall Image This is the same image and paragraph as above, except that I've added the clearfix class to the paragraph. Now, the paragraph expands to contain any floated elements.

I find the clearfix class to be a very elegant solution. It fixes the element with the issue (not neighboring elements), and it's very robust and reusable. All you need to do is add a clearfix class to each element that needs to expand to contain a floated element.

There's just two teensy little problems with the solution thus far - Internet Explorer 6 and Internet Explorer 7. They don't support the :after selector, so a bit more code, inside conditional comments, is required.

<!--[if lte IE 6]>
<style type="text/css">
.clearfix { height: 1%; }

<!--[if IE 7]>
<style type="text/css">
.clearfix { display:inline-block; }

That is how to corral escaping floated elements using clearfix, including an IE7 solution.

Photograph originally from APOD.


Tags: code css html

Authorized users may log-in to leave a comment.

Last Blog: Dress Up For the Holidays

Next Blog: I ♥ Musicals.