Generating Color Utility Classes in SASS
Per the recommendation of some friends, I’ve been using BassCSS on a few projects. It’s a CSS framework free of “side effects” that encourages using utility classes to style elements.
This approach feels weird at first, but has the fascinating effect of not requiring any modifications to CSS files, only additions. By doing so, it becomes possible to have the CSS be “done.” Because you are only adding to the CSS and you never have overlapping or conflicting rules, the CSS is less brittle.
The downside is that the HTML tends to bloat, and you are more explicitly mixing style with document structure.
Here’s how an H1 might look using BassCSS.
<h1 class="h1 bold blue sans-serif">Headline</h1>
Verbose, but explicit.
Color Utility Classes
The BassCSS Colors module adds in a few color classes.
For one of my projects, I wanted to create more color utility classes. These can be a pain to generate, due to their reptitive nature. Here’s how it might look for a declaration of $white
and its utility classes:
$white: #fff;
.white {
color: $white;
}
.bg-white {
background-color: $white;
}
.border-white {
border-color: $white;
}
That quickly becomes tedious as you add more colors. Using some SASS magic, we can DRY up how we define our colors by using SASS lists:
$color-list {
red #f00,
green #0f0,
blue #00f
}
@each $value in $color-list {
.#{nth($value, 1)} {
color: nth($value, 2);
}
.bg-#{nth($value, 1)} {
background-color: nth($value, 2);
}
.border-#{nth($value, 1)} {
border-color: nth($value, 2);
}
}
This will generate the appropriate color classes for each color contained in $color-list
. The above example will generate 9 utility classes in total. It makes adding a new color a one-line change, instead of a multiple-line change.
Enjoy!