CSS

Colours With Sass Map

Here is a quick CSS snippet on how you can use Sass maps to create a colour list for your project.

Sass maps are a nice way of creating lists, you can do multiple things with lists you can either loop through all of them or you pick a specific element from the list. If you've used other programming languages before a Sass map is essential an array of key value pairs.

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

This gives us a nice way of having a collection of the different colours we want on the entire website and then we can create a Sass function to get access to these colours.

$colours:
(
        ruby: #D8334A,
        grapefruit: #ED5565,
        bittersweet: #FC6E51,
        sunflower: #FFCE54,
        straw: #E8CE4D,
        grass: #A0D468,
        basil: #2ECC71,
        mint: #48CFAD,
        teal: #A0CECB,
        aqua: #4FC1E9,
        blue-jeans: #5D9CEC,
        lavender: #AC92EC,
        plum: #8067B7,
        pink-rose: #EC87C0,
        beaver: #BAA286,
        chocolate: #8E8271,
        light-grey: #F5F7FA,
        grey: #CCD1D9,
        dark-grey: #656D78,
        charcoal: #3C3B3D,
);

Then we can create a function in Sass by using the keyword @function with a parameter of the colour you want to use. Then we start off by creating an if statement to see if the colour you want exists in the map if not then we display an error message. Else then we use the function map-get to get the colour from the Sass map.

@function get-colour($colour) {

  @if map-has-key($colours, $colour) {
    $colour: map-get($colours, $colour);
  } @else {
    @if type-of($colour) != colour {
      @error "Colour name: `#{$colour}` not found.";
    }
  }

  @return $colour;
}

How To Use get-colour() Function

To use this function it's the same way as you would in any other programming language.

Below is an example of setting the background to black and the text colour to white.

.item
{
    background: get-colour(black);
    color: get-colour(white);
}

This will compile as:

.item
{
    background: #222;
    color: #FFF;
}

Looping Through Map

If you want to automatically create classes that use the colour names in the Sass map then you can do this by using the @each keyword.

@each $colourName, $colour in $colours {
    .text-#{$colourName}
    {
        color: $colour;
    }

    .bg-#{$colourName}
    {
        background: $colour;
    }
}

This creates a CSS class for both text and background colours of each of the colours in the Sass map. Therefore if you want to add a background of black and text white on an item then you can use the following in your HTML.

<div class="item bg-black text-white">
</div>

Demo

View the demo to see how these colours look on your website, Paulund Members can download all the demo files and Colour mapping.

flat-colours

Back to top

View Demo

Members Download