Fast color helpers with SASS Lists

Yep, it’s that time of the week again. Time for more insanely optimized helper classes in SASS.

Let’s talk about colors. So, say you have a list of color variables:

1
2
3
4
5
6
7
8
$blue:      #0ab0ed;
$blue-dark: #0064cd;
$green:     #8da1ae;
$red:       #f06338;
$yellow:    #e7dfb1;
$orange:    #f89406;
$pink:      #c3325f;
$purple:    #7a43b6;

You probably want some helper classes to pepper through your code, like .color-blue or .bg-blue. Fortunately, with SASS lists, this process is almost as easy as typing out the variables in the first place.

Set up a list:
variables_and_overrides.scss
1
2
3
4
5
6
7
8
9
10
$colors: (
  $blue blue,
  $blue-dark blue-dark,
  $green green,
  $red red,
  $yellow yellow,
  $orange orange,
  $pink pink,
  $purple purple
  );

Simple enough, right? Okay, now let’s set up our mixins.

Set up some mixins using interpolation and nth:
variables_and_overrides.scss
1
2
3
4
5
6
7
8
9
10
11
12
13
@mixin generate-colors() {
  @each $color in $colors {
    .color-#{nth($color, 2)} {
      color: nth($color, 1);
    }
    .bg-#{nth($color, 2)} {
      background: nth($color, 1);
    }
    .border-#{nth($color, 2)} {
      border-color: nth($color, 1);
    }
  }
}
Call your mixin:
variables_and_overrides.scss
1
@include generate-colors();
Lust at the beautiful helpers at your fingertips:
application.css
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
.color-blue {
  color: #0ab0ed; }

.bg-blue {
  background: #0ab0ed; }

.border-blue {
  border-color: #0ab0ed; }

.color-blue-dark {
  color: #0064cd; }

.bg-blue-dark {
  background: #0064cd; }

.border-blue-dark {
  border-color: #0064cd; }

.color-green {
  color: #8da1ae; }

.bg-green {
  background: #8da1ae; }

.border-green {
  border-color: #8da1ae; }

.color-red {
  color: #f06338; }
...
Side note on speed:

If you aren’t using it yet, I really encourage you to start using gulp-sass, which is built ontop of node-sass right now.

File saves are often under 200ms, which is practically instant; and you can get away with doing some pretty insane loops and code generation really quickly and easily. I’m working on a few Rails projects and plan on continuing to use this process instead of the native Rails SASS simply because the speed is extraordinary.