Query unused CSS rules on current document state
Last modification on
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:
(function() {
for (var i=0;i<document.styleSheets.length;i++) {
var rules = document.styleSheets[i].cssRules || [];
var sheethref = document.styleSheets[i].href || 'inline';
for (var r=0;r<rules.length;r++)
if (!document.querySelectorAll(rules[r].selectorText).length)
console.log(sheethref + ': "' + rules[r].selectorText + '" not found.');
}
})();
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.
Tested on Chrome and Firefox.