Unused css - how do you clean it up?

Konstantin K picture Konstantin K · May 24, 2012 · Viewed 8k times · Source

Probably any experienced web developer would be familiar with this problem: over time your css files can grow pretty huge and ugly because of all the no longer used selectors, which might be pretty tricky to find. I'm working on a rails project where we tend to re-design things quite frequently, which leads to a tonne of deadweight css. What's the best way to find and remove it?

Now, I do know that there is a rails plugin called deadweight built specifically for that purpose. However, here's my problem with deadweight: first of all, it completely ignores selectors used in javascript. Next, it scans only those pages that you configure it to scan which means there's a risk of removing something that is used on pages that you didn't scan for some reason. Finally, it finds unused selectors only in compiled css (we use LESS) - matching these against the actual code is a bit too involved.

I have also tried http://unused-css.com/ - they're great, but can't access localhost and, again, can only scan compiled CSS.

I really think there must be a better way of doing this. Actually, some time ago I decided to optimise one particular css file by grepping each selector in the entire project directory (emacs + rinari mode make it super-easy and super-fast), and each time I didn't see any html or css in the results I removed the style. Zero problems, worked like a charm. Obviously, I'm not going to do that for the entire site. However, I really don't believe that this couldn't be automated. Now, before I fire up my python and code this up, can anyone actually tell me if I'd be reinventing the wheel?

Answer

NARKOZ picture NARKOZ · Aug 10, 2012

Check out uCSS library from Opera Software.

It helps you to find unused CSS, as well as duplicate CSS. Also, you can get an overview of how many times each rule has been used in your markup. Several options are available by setting up a config file.

Update:

Another great alternative: csscss.

Written in Ruby and supports SASS, Less.

Update:

Another great alternative: uncss.

It works across multiple files and supports Javascript-injected CSS.