Removing Unnecessary CSS with Grunt and UnCSS

tl;dr version

While working on my portfolio I made myself a mental note to go back through the CSS and remove un-used CSS blocks. Since I was using Font Awesome (which is a really great icon font project), I knew I needed to manually remove a ton of styles that weren’t being used in the design. Things like the CSS animation section and all the icons I was not using from the library. As the project kept growing, I started to dread the day I would need to sift through the code and manually delete styles. It was turning into a daunting task.

Then I stumbled upon Addy Osmani’s article about grunt-uncss. The plugin uses PhantomJS to load your webpage and remove un-used CSS. Open Source FTW!

The biggest reduction in file size came from the Font Awesome library and the un-needed sections in the normalize.css file. All of those and a few others are concatenated into my master stylesheet using grunt.

After running the service, the results were a 53% (38kb -> 18kb) reduction in file size and an 18.5% (76ms -> 62ms) faster load time!

Caveats: the service removes CSS that may be needed conditionally. Like form validation styles for IE, or styles added using JavaScript; such as using responsive nav.

To prevent this, I ran uncss and created a new file titled styles-uncss.css. I then ran a diff against the original CSS file and the uncss version. This method allowed me to easily see what was removed. I then added bits back into the master CSS file which were needed that the plugin was not aware were needed.