Creating Utility Classes with Sass Maps

Alan Eicker
Level Up Coding
Published in
2 min readJan 28, 2020

--

As front-end developers, we’re always looking for ways to optimize our code and streamline our processes. CSS is no different. If you’ve spent a considerable amount of time working on projects you’ve most likely created a pattern library. Pattern libraries are essential in driving consistency across multiple products and streamlining development, but writing CSS for large codebases can be tricky and quite cumbersome.

Don’t Make Your Life Difficult

Part of what makes pattern libraries so useful are out-of-the-box utility classes that make adding things like margin, padding, font sizes and colors a snap. The problem is that depending on how many variations you have, creating and maintaining these utility classes can become a very tedious task.

Say you’re creating a utility class for font sizes and you have the following standard sizes: 12, 14, 16, 18, 20, 24, 28, 32, 36 and 40. We could easily create ten separate utility classes and call it a day. It might end up looking something like this:

This is by no means wrong, but we’d have to repeat this process every time a new font size is needed. Now imagine if we also wanted these utility classes for specific breakpoints like small, medum and large. It would become a very redundant and tedious chore to maintain our CSS if we continue to write our styles like this. Fortunately, there’s a better way!

The Power of Sass Maps

Sass maps are a powerful tool that changes the way we write our utility classes. We can significantly reduce the amount of CSS we have to write, making maintain our styles as easy as updating a few Sass variables. Let’s take a look at how we can achieve this.

In the previous example, we created some utility classes for ten font sizes. With Sass maps, we can rewrite that CSS like this:

The Sass above will loop through the breakpoint and font size lists and create ten basic utility classes and another ten for each breakpoint. That's a total of 40 utility classes! Now, if we need to add a font size, all we have to do is add it to the $font-sizes list. Doing this for all of your utility classes will save you a lot of time and make your life so much easier.

I hope you enjoyed this tutorial. Cheers.

--

--