Colour coding with SCSS each loops

Often my job requires me to create modules that a user can add and customise from a CMS. In many cases, they like to have control over the background colour of the module to fit with their brand colour palette.

I wanted to share the way in which I generally write this in SCSS, as some people might find it useful.

Here is an example of the html for the module they can add. They can select the background colour in the CMS and it comes through as a class name on the module, e.g. "green".

<section class="module green">
  <p>Content goes here</p>
</section>

In the SCSS file we can create a list of the colours called $brand-colors. Inside each bracket we have a string (the colour class name from the CMS), and the hex value or colour variable name, separated by a comma. You can add as many values as you like in here, but for this example I'll stick with two.

$brand-colors: ("red",$c-red),("green", #008000),("blue",#0000ff);

.module {
  @each $color in $brand-colors {
    &.#{nth($color,1)} {
      background-color: nth($color,2);
    }
  }
}

We can then declare an each loop, nested inside the styles for the module, which loops through each $color inside our list of $brand-colors.

The first part of this - &.#{nth($color,1)} - is referencing the first value inside our brackets within the $brand-colors list. So for this example, if we were to write this out the normal way, it would look like this:

.module {
  &.red {}
  &.green {}
  &.blue{}
}

The next part - background-color: nth($color,2); is referencing the matching variable or hex code within each set of brackets. Note that this doesn't need to be wrapped in #{}.

With an each loop like this, you can save a lot of time and many, many lines of code. It might seem like overkill for 2 or 3 colours, but this way also makes it easy to scale up if they decide they want more colours added in the future. The example I've used is for colour coding, but this can be used in various different ways, with different values/options.

I hope this is helpful in some way! Feel free to share ideas of how you might use this in a project.

For more reading: thesassway.com/intermediate/if-for-each-while