Skip to main content

Clean CSS variables using SASS maps


Maps in SASS/SCSS allow us to store pairs of keys and values, and make it easy to look up a value by its corresponding key. We can use a SASS map to generate and keep track of variables in a project.

Creating the SCSS map

First, let’s create our map. We have a list of 5 font weights, each with a name and a value.


$font-weights: ( "regular": 400, "medium": 500, "semibold": 600, "bold": 700, "extrabold": 800, );

Generating the variables

Now, we just need to generate our variables. We want each variable to follow the same naming convention, so we can make it really simple:


:root { @each $weight, $value in $font-weights { --font-weight-#{$weight}: #{$value}; } }

The code above will compile to this CSS:


:root { --font-weight-regular: 400; --font-weight-medium: 500; --font-weight-semibold: 600; --font-weight-bold: 700; --font-weight-extrabold: 800; }


To use my variables, I can simply write font-weight: var(--font-weight-semibold) (or another weight from my map).

p { font-weight: var(--font-weight-regular); }

This snippet has been useful when generating typography styles, as well as colour palettes. It adds a few lines of code but I think it makes it more readable, and it guarantees that your variable names are all consistent. Ultimately, this is really a matter of personal preference. For our font weight variables, here’s the difference between our code and plain old CSS:

:root { --font-weight-regular: 400; --font-weight-medium: 500; --font-weight-semibold: 600; --font-weight-bold: 700; --font-weight-extrabold: 800; }
$font-weights: ( "regular": 400, "medium": 500, "semibold": 600, "bold": 700, "extrabold": 800, ); @each $weight, $value in $font-weights { --font-weight-#{$weight}: #{$value}; }

To see an example with nested maps, have a look a the colour palette demo below.


import "./styles/styles.scss";

export default function App() {
  return (
      <ul className="button-group">
          <button className="button-primary">Primary</button>
          <button className="button-secondary">Secondary</button>