Skip to content

Instantly share code, notes, and snippets.

@arlodesign arlodesign/

Last active Dec 12, 2016
What would you like to do?
Compare CSS
  1. Download this gist into a csscompare folder

  2. npm install

  3. Create before and after folders. Your folder should now look like this:

     - /csscompare
     |- /after
     |- /before
     |- /npm_modules
     |- index.js
     |- package.json
  4. Copy your before and after CSS into the appropriate destinations

  5. node index.js

  6. Now look in the new compare folder and diff to your hearts content, either with a tool like FileMerge or diff -bur compare/before compare/after

var fs = require('fs');
var select = require('css-select');
var makeDom = require('htmlparser2').parseDOM;
var put = require('put-selector');
var audit,
audit = fs.readFileSync('./audit.txt', 'utf8');
styles = fs.readFileSync('./styles.css', 'utf8');
styles = styles.replace('@charset "UTF-8";', '');
// get the audited values as an array
foundSelectors = audit
.map(, String.prototype.trim);
// get the current file's selectors as an array
currentSelectors = styles.trim().split('}').reduce(function(result, selector) {
var selectorStr,
selectorStr = selector.split('{').shift().trim();
if (selectorStr.indexOf('@') !== -1 || selectorStr.indexOf(':') !== -1 || !selectorStr) {
return result;
selectors = selectorStr.split(',').map(, String.prototype.trim);
newResult = result.concat(selectors);
return newResult;
}, []);
// for each audited value, look for it in the existing css
deadSelectors = currentSelectors.reduce(function(result, selector) {
var el,
found = false,
if (foundSelectors.indexOf(selector) !== -1) {
return result;
// Sometimes the audit mixes some selectors up. For example, our CSS may have .one.two, but the
// browser reports it as So to TRUELY see if the selector was not found...
try {
// First, create an element based on the css selector (put-selector adds a line break that
// screws up htmlparser2, so we have to remove that)
el = put(selector.replace('*', 'div')).toString().replace('\n', '');
// Second, create a traversable DOM object out of that element
dom = makeDom(el)[0];
// Finally, see if the any of the selectors in our found selectors match the element
// Using a loop so we can break out of it
for (var s in foundSelectors) {
if (select.selectAll(foundSelectors[s], [dom]).length) {
found = true;
} catch(e) {
console.log('CHECK OUT THIS SHITTY CSS: ' + selector);
if (found) {
return result;
} else {
return result.concat([selector]);
}, []);
"name": "csscompare",
"version": "1.0.0",
"description": "Compare some CSS directories by normalizing the source",
"main": "index.js",
"author": "",
"license": "ISC",
"dependencies": {
"cssbeautify": "^0.3.1",
"glob": "^5.0.5",
"js-beautify": "^1.5.5",
"mkdirp": "^0.5.0",
"rimraf": "^2.3.2",
"uglifycss": "0.0.14"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.