Wednesday, April 10, 2013

Cleaning up a CSS

Let's say you have a CSS with a few thousand selectors and many many rules. Let's say you want to eliminate the unused rules, how do you do that?

I spent about an hour looking online for some tool that would easily clean up CSS files. I've ended up trying a few browser extensions:

  • CSS Remove and combine, for chrome, did not work for me. It would only parse the very first web site in my browser window, and seemed to refuse file:/// urls. I later on discovered that chrome natively supports this feature: just go in developer tools (ctrl + shift + i), click the audits tab, click run, and you will find a drop down listing the unused rules in your CSS.
  • Dust-me Selectors, for firefox, worked like a charm: it correctly identified all the unused selectors. 
In both cases, however, the list of unused selectors did not seem that useful, especially if there is thousands of them. I was really not looking forward to go through my CSS by hand. And remember you can really only remove a style if there are no selectors left.
In the end, I noticed that "Dust-me" allowed to export the list of unused selectors as a .csv file, and wrote my own script: https://github.com/ccontavalli/css-tidy to read this csv, parse the .css, and output a cleaned up version of it.

The result was pretty good, and in the end it saved me lot of work :-), have a look at it. Note that this also works with Chrome: all you have to do is feed css-tidy with a list of selectors to eliminate.

No comments:

Post a Comment