Query unused CSS rules on current document state

Last modification on 2010-04-21

Today I was doing some web development and wanted to see all the rules in a stylesheet (CSS) that were not used for the current document. I wrote the following Javascript code which you can paste in the Firebug console and run:

   1 (function() {
   2 	for (var i=0;i<document.styleSheets.length;i++) {
   3 		var rules = document.styleSheets[i].cssRules || [];
   4 		var sheethref = document.styleSheets[i].href || 'inline';
   5 		for (var r=0;r<rules.length;r++)
   6 			if (!document.querySelectorAll(rules[r].selectorText).length)
   7 				console.log(sheethref + ': "' + rules[r].selectorText + '" not found.');
   8 	}
   9 })();

This will output all the (currently) unused CSS rules per selector, the output can be for example:

http://www.codemadness.nl/blog/wp-content/themes/codemadness/style.css: "fieldset, a img" not found.
http://www.codemadness.nl/blog/wp-content/themes/codemadness/style.css: "#headerimg" not found.
http://www.codemadness.nl/blog/wp-content/themes/codemadness/style.css: "a:hover" not found.
http://www.codemadness.nl/blog/wp-content/themes/codemadness/style.css: "h2 a:hover, h3 a:hover" not found.
http://www.codemadness.nl/blog/wp-content/themes/codemadness/style.css: ".postmetadata-center" not found.
http://www.codemadness.nl/blog/wp-content/themes/codemadness/style.css: ".thread-alt" not found.

Just a trick I wanted to share, I hope someone finds this useful :)

For webkit-based browsers you can use "Developer Tools" and use "Audits" under "Web Page Performance" it says "Remove unused CSS rules". For Firefox there is also Google Page Speed: https://code.google.com/speed/page-speed/ this adds an extra section under Firebug.

Update: Tested on Chrome and Firefox.