Skip to content
HTML and CSS Sass

Using Sass Maps to Create BEM Modifier Classes

3 min read

Sass maps have been around for a little over a year now and are an incredibly useful feature of the CSS preprocessor.

If you’re already using them then you’ll already know how handy they are; if not, then hopefully this little post will give you a good start.

Introduced in Sass 3.3, maps are essentially associative arrays or hashs. They provide a way of storing key-value pairs. For example:-

$flash: (
    success: #dff0d8,
    warn: #fcf8e3,
    fail: #f2dede
);

Once we’ve defined a map we can retrieve its values using the map-get() method like this:-

color: map-get($flash, warn); // outputs: color: #fcf8e3;

Now let’s use our $flash map and create some BEM modifier classes.

If you’re not familiar with BEM and modifier classes then take a look at CSS Tricks’ BEM 101. Essentially we’re creating classes that when combined with another alter the latter’s styles.

As an example we’re going to create a flash class for styling a flash message that we can modify depending on the nature of the message. For example, to show an error message we’d combine the two classes flash and flash--fail. .flash defines the basic styles for the flash message and .flash--fail alters the background and border colours.

First we define the basic styles for our flash message. This is our .flash block class:-

.flash {
    border: 1px solid;
    padding: 1em;
    margin-bottom: 2em;
}

Now we’re ready to define our modifier classes using our $flash map. For this we are going to use Sass’ @each to loop through each key-value pair in the map:-

.flash {
    @each $name, $color in $flash {
        &--#{$name} {
            background-color: $color;
            border-color: darken($color, 20%);
        }
    }
}

We’re using &--#{$name} to extend the .flash class name so that we get the following classes: .flash--success, .flash--warn and .flash--fail. We’ve also used darken() to change the border colour of our flash message so that it is a 20% darker shade of the background colour.

Finally let’s pull this altogether:-

.flash {
    border: 1px solid;
    padding: 1em;
    margin-bottom: 2em;
    @each $name, $color in $flash {
        &--#{$name} {
            background-color: $color;
            border-color: darken($color, 20%);
        }
    }
}

You can see this in action on SassMeister.

Hope that’s inspired you to take a look at Sass maps and get creative.

© 2024 Andy Carter