Clean Up CSS code Removing Unused Selectors

If you created your website using a website template, you may not use all the CSS selectors of this template. Moreover, if you use the famous Twitter bootsrtap “framework”, many parts of the CSS code probably are not in use.

Google recommends to Remove unused CSS

Before a browser can begin to render a web page, it must download and parse any stylesheets that are required to lay out the page. Even if a stylesheet is in an external file that is cached, rendering is blocked until the browser loads the stylesheet from disk. In addition, once the stylesheet is loaded, the browser’s CSS engine has to evaluate every rule contained in the file to see if the rule applies to the current page. Often, many web sites reuse the same external CSS file for all of their pages, even if many of the rules defined in it don’t apply to the current page. The best way to minimize the latency caused by stylesheet loading and rendering time is to cut down on the CSS footprint; an obvious way to do this is to remove or defer CSS rules that aren’t actually used by the current page.

It is important to remove the unused CSS selectors to speed-up browser rendering of your website. Luckily, there are many tools available to help you in this procedure.

Dust-Me Selectors Firefox extension is my favorite solution, but there are many other solutions.

Firefox: Dust-me selectors extension

Dust-Me Selectors is a Firefox extension (for v1.5 or later). You can install it here.

It extracts all the selectors from all the stylesheets on the page you’re viewing, then analyzes that page to see which of those selectors are not used. The data is then stored so that when testing subsequent pages, selectors can be crossed off the list as they’re encountered. You can test pages individually, or spider an entire site, and you’ll end up with a profile of which selectors are not used anywhere.

Right click on page and select “Spider this page…”

Press Start to analyze your site.

The result is

Chrome Developer Tools

Open Chrome Developer Tools (CTRL+SHIFT+I) and go to Audit tab. Select “Audit Present State” and click “Run”.

Here are the results:

Online tools

GTmetrix

You can use GTmetrix to clean up CSS code at http://gtmetrix.com/remove-unused-css.html. Give the URL and press GO!

Results:

unused-css.com

unused-css.com is an another online tool to clean up your CSS code. There is a PRO version avaliable, which creates the “clean” CSS. To download it, you have to subscribe to paid version.

Other software

mincss

mincss is a python script. As its creator Peter Bengtsson explains, mincss is a tool that when given a URL (or multiple URLs) downloads that page and all its CSS and compares each and every selector in the CSS to find out what isn’t used. The result is your original CSS file with those unused selectors (not found in your HTML) removed.