Clean colour management with Sass

Ryan Taylor
Dec 16, 2014 · 1 min read

I thought I’d share a little setup I’ve been using for colour management in my projects and it’s all thanks to the new Sass Maps data type.

There have been a few tutorials discussing the use of maps. Jason Garber’s Sass Maps Are Awesome! is especially worth a read.

In my case I wanted to use Maps to reduce the number of long colour variable names I was using. e.g.

$site-footer-title-color: #FFF;
$site-footer-info-border-color: rgba(#FFF, 0.1);

Using Maps I’ve started to group colours based on element into a single variable:

$colors: (
nav: (
text: #333,
text-hover: #FFF,
bg: #FFF,
bg-hover: #FEF160
),
site-footer: (
title: #FFF,
info-border: rgba(#FFF, 0.1),
bg: #2A3137
)
);

The trouble with nesting maps like this is that to retrieve them we’d use:

.site-footer {
background-color: map-get(map-get($color, site-footer), bg);
}

This however is very ugly so I also have a helper function:

@function color($el, $color, $map: $colors) {
@return map-get(map-get($map, $el), $color);
}

This lets us do this:

.nav {

a {
background-color: color(nav, bg);
color: color(nav, text);

&:hover {
background-color: color(nav, bg-hover);
color: color(nav, text-hover);
}
}
}
.site-footer {
background-color: color(site-footer, bg);
}

Voila! A nice clean way of handling colours with Sass.

    Ryan Taylor

    Written by

    Technical Director at @nodivide, creator of @leeve_app & @getastrum. Author of Version Control with Git (https://gumroad.com/l/rXch). Husband & father.