Removing Unused CSS Selectors Using UnCSS

A very easy way to speed up the front end development of your website is to a) use a decent UI framework (Bootstrap being the obvious answer here but there are others) and b) buy a theme that's based on said framework. Descent themes normally come with a variety of different layouts giving multiple options for your website (e.g homepage, blog & search results). You can then select which parts you like, move them across to your website and ignore the rest.

A side effect of scaffolding your website in this manner is that you normally have no choice but to include the full CSS file that came with the theme (unless they've kindly separated it out into lots of smaller files using a pre-processor like SASS - this, however, is not the norm).

Large CSS files, full of redundant selectors, increases both cognitive overhead when making changes and the amount of work needed by a browser to to download and parse your stylesheet - not to mention making your code feel dirty. Manually cleansing the file would have been tedious and error prone, I was looking for a better way.

One of the newsletters I subscribe to, CSS Weekly, recently intoduced UnCSS, a Node based tool to do just this. It runs a set of urls you specify, using the headless Phantom.js browser (thus also executing Javascript), and strips out all of those pesky unused selectors from your CSS. And it works surprisingly well!

For me, the easiest way to get it up and running was to use gulp (although it also supports other javascript build systems and the command line). I created a gulp task and passed in the un-minified version of my CSS file, all of the unauthenticated urls to my application (there doesn't seem to be a way to pass through authentication information at the moment) and the location where I wanted the clean CSS file to be generated.

It looked like this:

Once that was in place, a simple call to "gulp uncss" kicked off the task and 10 or so seconds later (it's that fast) out popped a CSS file minus the selectors that UnCSS thought no longer appled.

After manually comparing both the old and the new files, the only selectors that were missed were the obvious ones on authenticated pages and a couple pertaining to interactions with the site (at the moment, you can't tell it to click buttons etc).

The best bit was that my stylesheet dropped from 54Kb to 14Kb (an almost 400% improvement) and most importantly shaved off a lot of complexity. Exactly what I was looking for!

Author image
About Jon Leigh
London Website

Hi, I'm Jon. I'm part of the Engineering team at Moneybox, a London based Fintech startup helping people to save and invest.

In my spare time, I've created CompareVino, a UK supermarket wine comparison website. If you like wine and buy it from a supermarket, you should definitely check it out.

If you want to get in touch, send me a message via Twitter