Generating CSS classes with Sass

Thabo T
Simple Frontending

--

Using Sass can be really helpful in punching out some mundane repetition classes. In this example we use the each operator to go through a map list and generate some reusable css classes.

Given :

$myAppColours: (
success: #2ECC71,
info: #34495E,
warning: #F89406,
error: #EF4836
);

we can then use the each to loop through the values and generate some classes.

@each $state, $colour in $myAppColours {
.bg-#{$state} {
background: $colour;
}
}

This will generate these classes for you:

.bg-success {
background: #2ECC71;
}
.bg-info {
background: #34495E;
}
.bg-warning {
background: #F89406;
}
.bg-error {
background: #EF4836;
}

We can even take it further by generating variations of those colours by using more functions from sass(lighten). Taking the above example we can add to it:

@each $state, $colour in $myAppColours {
.bg-#{$state} {
background: $colour;
}
.bg-#{$state}--light {
background: lighten($colour, 10%);
}
}

which, as you probably guessed will generate:

.bg-success {
background: #2ECC71;
}
.bg-success--light {
background: #54d98c;
}
.bg-info {
background: #34495E;
}
.bg-info--light {
background: #46637f;
}
.bg-warning {
background: #F89406;
}
.bg-warning--light {
background: #faa937;
}
.bg-error {
background: #EF4836;
}
.bg-error--light {
background: #f37365;
}

So as you can see, with some simple SASS you can minimize the amount of code you have to write, while also keeping your code clean and maintainable. But with power comes responsibility and these functions that make our code easier to write can also lead us into a very dark place. So ALWAYS keep it simple and you will be good.

--

--