James Croft

DRYing up CSS colours with Sass

When writing Sass, it’s common to assign colours to variables. This is so that if the colour ever needs to change then the change only needs to be made in one place.

$royal-blue: #4169E1;

h1 { color: $royal-blue; }
.info-box { border: 1px solid $royal-blue; }

In practice, I sometimes find myself specifying the colour inline rather than using a variable. It may be because I think I’m only going to use the colour once, or maybe I just have the hex value handy and it’s easier than looking up the variable name.

So, I put together a unix command that I can run against my Sass stylesheet folders which will show me any duplicate colours.

grep -oRIh '#\w\{3,6\}' app/assets/stylesheets | sort | uniq -c | sort -r | awk '$1>1'

The output shows me which colours I should be using variables for and a count of how many times I’ve been bad:

   7 #98C93C
   5 #C0B0A8
   4 #E8E2DE
   4 #6B5F58
   3 #DCD2CB
   3 #8475B5
   3 #62ADC9
   2 #FCFAF5
   2 #FCB20D
   2 #F5301F
   2 #EAE4E1

Now the only problem is how to name the colour variables. David Walsh has a solution to that.