CSS Hackz Series: Clearing Floats with the Clearfix Hack

Published Wednesday, June 18, 2008 @ 8:59 am • 10 Responses

I use the CSS clearfix hack on nearly all of my sites. The clearfix hack — also known as the “Easy Clearing Hack” — is used to clear floated divisions (divs) without using structural markup. It is very effective in resolving layout issues and browser inconsistencies without the need to mix structure with presentation. There are countless variations of the clearfix hack around the Web, and for some sad reason, I keep a file updated with all of them. Recent pruning of my clearfix collection yields two excellent float-clearing techniques:

First clearfix method: addresses several reported rendering and display bugs by declaring very small values for both font-size and height, while also declaring a zero line-height value. A little paranoid perhaps, but the unique declarations seem to have no unintended/negative side-effects. This method also targets IE exclusively for the inline-block declaration. Check it out:

/* effective yet slightly paranoid clearfix hack */
.clearfix:after {
	visibility: hidden;
	font-size: 0.1em;
	display: block;
	line-height: 0;
	height: 0.1px;
    	content: " ";
	clear: both;
	}
* html .clearfix { display: inline-block; }

/* hide from ie mac \*/
* html .clearfix { height: 1%; }
.clearfix { display: block; }
/* end hide from ie mac */

Second clearfix method: highly refined version of the original clearfix hack by yours truly. This slightly enhanced, universal clearfix hack avoids unnecessary declarations and is perfect for clearing floats virtually anywhere and everywhere. I use this exact code on many different sites:

/* slightly enhanced, universal 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; }
/* stop commented backslash hack */

Next up..

Next in the CSS Hackz Series: Targeting and Filtering Internet Explorer 7! Stay tuned!


Dialogue

10 Responses Jump to comment form

1Louis

June 18, 2008 at 1:47 pm

Great memo, thank you Jeff.

2teddY

June 19, 2008 at 12:50 am

Thanks for the clearfix hack, Jeff! Although I’ve heard of it before, I only implement it in certain conditions when the clar:both attribute didn’t help.

But you right about the not mixing up content and styling - I extensive use <div style=”clear:both”></div> throughout my design. It doesn’t work for Wordpress’ richtext editor because Wordpress simply removes blank spaces. Clearfix will be the best solution if you want to clear certain floated content in a Wordpress post or page.

3Andy

June 19, 2008 at 3:09 am

Does anyone actually use IE Mac any more? I’m getting fed up of seeing people still putting this hack in their code. Fail.

4Travis

June 19, 2008 at 7:10 am

@Andy - According to stats on one of my sites, about 6% of my visitors use ie/mac- small percentage to be sure, but why not make the site use-able for as many people as you can? Especially when the fix is so easy, valid and semantic.

Cheers Jeff, this is a great little hack!

5Eric

June 20, 2008 at 11:32 am

I don’t remember how I found your blog but I’m really glad I subscribed.

Thanks for the tips
- Eric

6Perishable

June 23, 2008 at 3:42 pm

@Louis, @teddY: Thanks for the feedback, it really is great to have such excellent readers! Sorry about the delay in getting back to some of these comments, it has been an insanely busy month around here. That said, your comments are definitely appreciated! Great point about the WordPress rich-text editor as well, teddY — thank you! :)

7Perishable

June 23, 2008 at 3:52 pm

@Andy: trust me, I am just as sick and tired as you are when it comes to accommodating old broken browsers, especially IE Mac and IE 6. We hates them, really. Nonetheless, as Travis so eloquently explains, people should come first when it comes to providing information and delivering content. According to my statistics, there remain a modest number of folks out there still using IE/Mac, and quite a bit more using IE 6, obviously. Without putting a gun to anybody’s head and forcing them to upgrade their browser, it is necessary to use any means necessary to deliver consistent, usable, and accessible web design to as many browsers as possible. Thus, even though the clearfix hack is a bit unsightly on the eyes, it accomplishes this goal as Travis says, with a fix that is “easy, valid and semantic.” It’s a “win-win,” in my book ;)

8Perishable

June 23, 2008 at 3:54 pm

@Eric: Thank you — you just made my day! :)

9Ryan Williams

June 26, 2008 at 1:58 am

For a long time now I’ve been using the overflow way of clearing, which basically involves:

1. Set the parent container to ‘overflow: hidden;’ (or anything other than ‘auto’). This forces the browser to calculate where the container should end as it needs to know where to start clipping (although this never actually happens unless you give it a static height).

2. Give the container a ‘width: 100%;’, or anything else that throws IE6 into layout mode. This will make IE6 interpret the overflow in the same way as other browsers.

This works in all cases I’ve encountered so far, but is only tested in IE6, IE7, Firefox, Safari, and Opera.

If anyone wants to discuss the pros/cons of this method and suggest improvements it’d be appreciated as the clearfix method seems very bulky in comparison.

10Perishable

June 29, 2008 at 2:06 pm

Hi Ryan, I have used the overflow: hidden method on one of my other themes for this site. It works well in most browsers, however in Firefox it causes the vertical scrollbar to disappear when the width of the browser window is smaller than that of the floated division. The second method I have not yet tried, although in my experience setting width: 100% tends to produce unwanted side-effects, especially in complex layouts. Nonetheless, these are both good techniques, and I plan on exploring the second method more fully in subsequent designs. Thanks for the info! :)

Subscribe to comments on this post


Share your thoughts..

TopRead official comment policy

Contact Perishable Press

  • Contact Jeff via form

Search Perishable Press

About Perishable Press

Perishable Press is the virtual playground of Jeff Starr — visionary, founder and lead developer of Monzilla Media, a small web and graphic design company in the lush desert oasis of Moses Lake, Washington. Perishable Press features articles and tutorials on many aspects of digital design..

Read more..

Perishable on Twitter

automation is great: i've got photoshop batch processing 300+ images while FTP is simultaneously uploading them to the server..

Perishable on Tumblr

Tons of Firewalls

Tuesday, 7 October 2008, 1:45 am

Recently overheard on conservative talk radio (instructing listeners how to obtain a free promotional video from their new website):

“This website has tons and tons of firewalls, so you have to use your real email address to download the video..”

The Quiet Search Revolution

Monday, 6 October 2008, 12:15 pm

Just a thought.. As awesome as Google is these days, it would suck if they ended up owning the entire search-engine business. When they get to the point where all competition is impossible (due to their sheer size, financial resources, media influence, etc.), how many alternate search engines will have the resources for continuous improvement and top-quality search results? When this happens, we will have no choice but to do exactly what Google tells us to do.

As deeply ingrained as it is for everyone to instinctively and unthinkingly turn to Google for their search activity, it is time to leave a few alternate search tabs open for as much use as possible. Instead of using Google just because that’s what you always do, try your search on MSN, Yahoo, Ask, or any of the other independent search engines instead. Sharing traffic with other search engines is a nice, quiet way to keep the competitive spirit alive and well in the search-engine business.

Disappearing WordPress Posts

Wednesday, 1 October 2008, 7:50 pm

Today I experienced difficulties while trying to publish or even save new posts in WordPress. I would compose the post as usual, add all of the keywords, tags, meta tags, and so on, but as soon as I clicked the “Publish” or “Save” button, the post would just disappear from existence.

The weird thing is that during the drafting process, WordPress’ default auto-save feature showed that the post had been saved at expected intervals. Unfortunately, after trying to publish several different posts, WordPress showed absolutely no record of the posts ever being created. They simply vanished into thin air.

Fortunately, a little investigation revealed the culprit. If you should find yourself dealing with this same issue, here are some different things that you should try. First, re-upload fresh copies of your entire WordPress installation. I don’t know why exactly, but apparently various files can either go stale or completely disappear from the server. Overwriting or writing fresh files may do the trick.

If that doesn’t work, check your WordPress database for errors. In my case, a little investigation revealed that something had caused a couple of fatal errors in the wp_posts table. Fortunately, checking and repairing the table solved the issue.

Tumblr Battles

Wednesday, 1 October 2008, 5:30 pm

Please excuse the duplicate Tumbr posts.. seems there is no way to ping Tumblr to refresh/rebuild the RSS feed according to changes in post content. So, to resolve the issue I have discussed now like two or three times regarding paragraph elements and proper feed formatting, I have no choice but to repost a majority of my text posts.

This is necessary for the proper import and display of my Tumblr feed into WordPress. Currently, there are five items displayed at once, each styled according to proper inclusion of paragraph tags. Thus, whenever the Tumblr feed “forgets” to enclose single-paragraph posts with the proper tags, the result is an unstyled post entry displayed on my site.

Assuming that makes sense, you will please excuse my dust while I repost a few older entries in an attempt to reconstruct (the hard way) a properly formatted Tumblr feed.

More Optimization Measures

Wednesday, 1 October 2008, 5:27 pm

Another important step in improving the performance of my recent redesign involves the optimization of both CSS and JavaScript content. During development there were around 15 server requests for these two types of files, 10 JavaScript files and 5 CSS files. This was okay for my own use, but would not work for production purposes.

Optimizing these file types involves consolidation, compression, and caching. Consolidation of 10 JavaScript files into three is huge improvement. Now I deliver one JS file for the functionality of the site, one for Mint, and another for Analytics. Likewise for the stylesheets; after consolidation, a single stylesheet is delivered to all modern browsers. There are two additional stylesheets as well, but they are targeted at IE6 and mobile browsers and will not load elsewhere.

Once the files were consolidated as much as possible, it was time to optimize or “crunch” them. Using the sexy Flumpcakes CSS optimizer, I was able to reduce my stylesheets by around 25%. Likewise for JavaScript, I used xtreeme.com’s optimizer to shave an additional 20% off the size of my JS content.

Finally, once I had consolidated and compressed my JS and CSS files as much as possible, I wanted to further my optimization efforts by ensuring that these files were cached by the browser. By setting far-future Expires headers for everything but the statistical files, my site gains an additional performance boost by eliminating the need to reload preexisting content.

Read more on Tumblr..

Subscribe to Comments Recent Dialogue

  • Adam Singer: Thanks for this. You're right, if it isn't broken, don't fix it. I was about to update my permalinks and install a plugin to redire...
  • Marilyn: It looks great on my browser! I wish I had that much creativity in my head! It's gorgeous!...
  • Randy: "Too girly?" It looks like a great design. Define "too girly!"...
  • Christopher Ross: .htaccess based redirects are wonderful. I'm always baffled by web professionals who don't take the time to learn more about them....
  • federico: Hi Jeff... tnx so much...it worked perfectly... c u Federico...
  • Cooltad: The skin seems (mostly) fine in my expert opinion. Your one of the few people able to make a design with a transparent table and a b...
  • Neal: The free Intro to Linux book is a great place to start http://www.ischool.utexas.edu/mirrors/LDP/LDP/intro-linux/html/index.html ...
  • Louis: @Jeff: Your “Archives” page is slick, although I would expect a cleaner implementation from such a vehement advoc...
  • Jeremy: Well I think that you may be over-critical, I don't see a darn thing wrong with it - I like it a lot!...
  • Jeff Starr: Alright, this is exactly the kind of information I was hoping to get. Lots of great ideas and recommendations here. I will be reading...

Read more recent comments..