SASS Maps

From SASS V3.3 onwards you can now play around with SASS Maps and let me tell you they are sweet!

If you ever needed to write out a bunch of classes for future use, eg:

// Foreground colours
.color-red { color: red; )
.color-blue { color: blue; )
.color-green { color: green; )

// Background colours
.bg-color-red { background-color: red; ) 
.bg-color-blue { background-color: blue; )
.bg-color-green { background-color: green; )

If this list was quite extensive, say 15 items it would take us a while to write out and and would be counter productive as we might as well use the power of SASS to write it out for us.

The maps work as key value pairs in this format:

$map: (key1: value1, key2: value2, key3: value3);

So for our colours lets start by writing out the map:

$colours: (
    red: red,
    blue: blue,
    green: green
);

We could then iterate over the map with the SASS Each Directive like so:

@each $colour, $theColour in $colours {
    .colour-#{$colour} {
        color: $theColour;
    }
    .bg-colour-#{$colour} {
        background: { color: $theColour; }
    }
}

That would give us the output we need, quickly and easily. If we needed to change a colour, we'd only have to change it in one place.

So we've got easy to maintain code, which is fast to reference.

If for some reason, you'd just need to reference the one colour somewhere else. you can do that like so:

.other-blue-class {
    background-color: map-get($colours, blue);
}

And that's it. I hope you find it as useful as I did.