Lessons Learned Concerning the Clearfix CSS Hack

Published Tuesday, February 5, 2008 @ 10:08 am • 13 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. Over the course of the past few years, I have taken note of several useful bits of information regarding the Easy Clear Method. In this article, I summarize these lessons learned and present a (slightly) enhanced version of the clearfix hack..

Use a space instead of a dot to prevent breaking layouts

Here is the defacto implementation of the clearfix hack, as presented in one of the original articles covering the method:

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

.clearfix {display: inline-block;}

/* Hides from IE-mac \*/
* html .clearfix {height: 1%;}
.clearfix {display: block;}
/* End hide from IE-mac */

Notice the line containing the content: "."; property. I have found that the period (or dot) specified in quotes has a nasty tendency to break certain layouts. By adding a literal dot after the .clearfix division (i.e., via the .clearfix:after selector), the clearfix hack creates a stumbling block for certain browsers. And not just for Internet Explorer — depending on the layout, even Firefox will choke a layout upon tripping on an :after-based pseudo-dot. The solution to this subtle design chaos? Replace the literal dot with a single blank space: "content: " "; — this trick has proven successful so consistently that I now use it as the default property in every clearfix hack that I use.

/* drop the dot, replace with space */
.clearfix:after {
     content: " "; 
     display: block; 
     height: 0; 
     clear: both; 
     visibility: hidden;
     }
     .
     .
     .

Add a zero font-size property to make it all smooth

Another bizarre inconsistency involved with clearfixed (probably not a real verb) layouts seems to disappear when the font-size property is included in the hack and subsequently set to zero:

/* zero font-size added to prevent potential layout issues */
.clearfix:after {
     content: " "; 
     display: block; 
     height: 0; 
     clear: both; 
     visibility: hidden;
     font-size: 0;
     }
     .
     .
     .

This may be overkill when using a blank space instead of an actual dot (as described above), but I honestly don’t care. I’m like some sort of CSS animal — using every available weapon to fight hellish layout battles. Looking back, I think I may have implemented this solution before discovering the empty-space fix. Yet some browsers may process white space as text, so it may prove beneficial nonetheless. Maybe, maybe not — I’m going to throw it out there for all of you CSS gurus to trip on.

Beware of misinformation regarding this method

No, I am not trying to warn you against the tips offered in this article — you will find they are quite harmless. Instead, I am referring to erroneous information found elsewhere on the Internet and even in printed form. Here is a presentation of the clearfix hack as presented in Joseph W. Lowery’s otherwise excellent book, CSS Hack & Filters:

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

.clearItem { display: inline; }

/* Start Commented Backslash Hack \*/
* html .clearItem, * html .clearItem * {height: 1%;}
.clearItem { display: block; }
/* Close Commented Backslash Hack */

Yikes! Do you see the problem? Actually, there are two potential issues in Mr. Lowery’s “.clearItem” hack. The first one is the deprecated use of the inline value for the display property in the middle .clearItem declaration:

.clearItem { display: inline; }

..as discussed in the original article, the property value here should be inline-block to fix floats on IE/Mac:

.clearItem { display: inline-block; }

The second flaw in Mr. Lowery’s “.clearItem” hack involves the * html .clearItem * selector in the following line:

* html .clearItem, * html .clearItem * {height: 1%;}

The first selector in this line is all that is required to achieve a successful hack. The second selector, however, effectively sets the height to 1% for all Internet Explorer browsers. This sucks, and I found out the hard way: after a month or so of using this version of the hack, I discovered that around half of my visitors (i.e., those using IE) were unable to leave comments because all of the form fields were only 1 pixel tall! Fortunately, it did not take too long to hammer down the culprit: the nefarious CSS wildcard selector ( * ) as seen in the erroneous code above. After deleting that second selector, everything clicked.

So what’s the moral of the story here? Simple. Always double-check your code and think critically before blindly copying & pasting your way to victory. Even professional writers and programmers make mistakes, so be sure to pay attention and make no assumptions.

All together now..

Putting everything together and combining these lessons learned with the original (correct) version of the Easy Clear Method, we fashion the following, fully functional, flaw-fixing clearfix formula:

/* 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; }
/* close commented backslash hack */

..and that’s a wrap! I sure hope you had as much fun as I did while writing this article.. if not, hopefully this round of “lessons learned” presented you with some useful information regarding the omnipresent, ever-useful clearfix hack. And finally, as this post focuses on CSS, I expect nothing less than the severest of criticism 1 concerning the ideas presented herein. — Fire away, all you crazy CSS heads! ;)

Note

  • 1 A bit of sarcasm for you ;)

Dialogue

13 Responses Jump to comment form

1David Tapper

March 4, 2008 at 4:31 pm

What is your opinion on using overflow:hidden? This seems to achieve the same effect and is a bit simpler.

.clearfix {
overflow: hidden;
}

* html .clearfix {
height: 1px;
overflow: visible;
}

It requires the holly hack to work in IE, but otherwise seems to work perfectly.

Also, what do you mean display:inline is deprecated? First I’ve heard of this! Is this some CSS3 thing?

2Perishable

March 4, 2008 at 4:49 pm

Of course, in general there is nothing wrong with using the overflow method, the float everything method, or any other method with which you feel comfortable. For me, it all depends on the compositional requirements of the layout in question. Hiding overflow has its disadvantages, just like any other method (including this one).

As for my misleading use of the term “deprecated,” you can relax — I meant it in a strictly general sense, as if to say that the use of inline has long-since been replaced with inline-block for the purposes of this hack. Rest assured, the inline property value isn’t going anywhere anytime soon ;)

3David Tapper

March 4, 2008 at 5:21 pm

Thanks, you had me worried for a moment :P

4Andy

March 12, 2008 at 11:13 am

Another issue with the line:

* html .clearItem, * html .clearItem * {height: 1%;}

is that I’ve found that grouping IE6 * html hacks renders them useless. You need to keep them separate.

5Perishable

March 12, 2008 at 1:24 pm

Excellent information, Andy — thank you for sharing it with us! :)

6Kate Stringer

May 1, 2008 at 8:51 am

Is there a reason to use height:1% vs height:1px? We have the following on our site which is working for the most part:

/* Clear Fix */

.cf:after { content: "."; display: block; height: 0; clear: both; visibility: hidden; }
.cf { display: inline-table; }
.cf { display: inline-block; }

/* Hides from IE-mac \*/

* html .cf { height: 1%; }
.cf { display: block; }

But we now have a very long page and in IE all the divs with the clear fix class are getting blown out. I’m wondering if this is because the 1% height relative to the height of the page is much larger on this long page? Is there any problem in using height:1px instead?

7Perishable

May 4, 2008 at 7:59 am

Hi Kate, I have used both versions (1px and 1%) on many occasions and have not experienced any significant issues with either. One minor issue that I did encounter while using height:1px; involved the nested div not centering correctly in the parent div. This issue occurred in IE6 only, and was resolved by adding a position:relative; declaration along with the height:1px;. Beyond that, your reasoning is correct concerning the use of height:1%;. You should be fine using height:1px; as an alternative, however I do recommend proper testing as well. ;)

8Andy Ford

May 15, 2008 at 12:51 pm

@David Tapper
I’ve relied on overflow:hidden in many situations, but it can come back to bite you in some cases.

In particular, if you have say a decorative transparent PNG that you’ve absolutely positioned partially in and partially out of the parent container with the overflow:hidden property set, then the PNG will be cropped at the boundary of the parent container.

This would apply to any element that is for whatever reason absolutely or relatively positioned partially or entirely out of the parent container.

On a separate note, I hate adding the clearfix class to the markup, so I’ve taken to just adding additional selectors in the css. Like so:

.clearfix:after,
.sidebar:after,
#footer:after {...}

adds a little cruft to the css, but keeps the html a little more pure.

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

mmmm, dark chocolate..

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

  • Nyx: Happy to have helped! Love your site....
  • dockside: Hi i want to use this code on my blog. but not for all post. I want 3 or 4 full posts and then post in double column How?...
  • NZ Beats: Got it working using the following: http://www.nzbeats.com/?feed=rss2&category_name=album-review...
  • Paul: Holy crap, you just saved my A$$! Thank you!...
  • free games: Google have a content distribution network here http://code.google.com/apis/ajaxlibs/documentation/#AjaxLibraries where you ca...
  • free games: Found this (untested) for those that just want https For HTTPS: var pageTracker = _gat._getTracker("UA-XXXX-1"); pageTracker...
  • H5N1: The question is very hard. No way to solve it in only few words :) First of all you need a Linux. OK. But Linux it's only a Kerne...
  • gowers: wow, your theme is so great, I like it...
  • Eric Ferraiuolo: Like some people are commenting, a virtual solution is going to be the easiest to get going with the least number of issues. I would ...
  • Brent Terrazas: Thanks for the mention, I currently am running Ubuntu Server 8.04 on VMWare Fusion beta (it's a free beta download.. check it out fo...

Read more recent comments..