Sub topic 10
Maps for design tokens
This chapter assumes you can write Sass variables, nest rules, and write a basic mixin. It also assumes you have seen @use load a module. Maps are a small topic with a few sharp edges, so the chapter covers both the syntax and the mistakes that cost the most time.
What a map is
A map is a Sass value that holds key-value pairs. It is written in parentheses, with a colon between each key and value and a comma between pairs. A map is stored in a variable like any other value.
Design tokens are the named values behind a visual design: colors, spacing steps, breakpoints, font sizes. A map keeps related tokens in one place and under one name. That beats a row of unrelated variables such as $color-primary, $color-danger and $color-warning.
$colors: (
primary: #3366cc,
danger: #cc3333,
muted: #777777
);Maps exist only at compile time. The browser never sees them. You can't write color: $colors;, and Sass reports an error if you try. A map has to be read with a function or looped over with a directive before it produces any CSS.
Reading values with map.get
Built-in map functions live in the sass:map module. Load it with @use and call functions through the map namespace. The module system gets its own chapter later. For now you only need the line below.
@use 'sass:map';
$colors: (
primary: #3366cc,
danger: #cc3333
);
.alert {
color: map.get($colors, danger);
border-color: map.get($colors, primary);
}This compiles to:
.alert {
color: #cc3333;
border-color: #3366cc;
}These functions cover most day-to-day work:
| Function | Returns |
|---|---|
| `map.get($map, $key)` | The value for the key, or `null` if the key is missing |
| `map.has-key($map, $key)` | `true` or `false` |
| `map.keys($map)` | A comma-separated list of keys |
| `map.values($map)` | A comma-separated list of values |
| `map.merge($a, $b)` | A new map with the pairs of `$b` added to or replacing those in `$a` |
Generating rules with @each
@each can unpack each pair into two variables. This is the most common use of a token map. One map becomes a family of utility classes.
$colors: (
primary: #3366cc,
danger: #cc3333
);
@each $name, $value in $colors {
.text-#{$name} {
color: $value;
}
}The #{$name} part is interpolation. It inserts the key into the selector text. The output is .text-primary and .text-danger, each with its color.
Adding a token to the map now adds a class with no other edits. Removing a token removes its class. The map is the single source of truth.
Nested maps
A map value can itself be a map. This groups tokens by category.
@use 'sass:map';
$tokens: (
colors: (
primary: #3366cc,
danger: #cc3333
),
spacing: (
sm: 0.5rem,
md: 1rem,
lg: 2rem
)
);
.panel {
padding: map.get($tokens, spacing, md);
background: map.get($tokens, colors, primary);
}map.get accepts several keys and walks down one level per key. If any key along the path is missing, the result is null.
You can loop over one branch of a nested map by fetching it first:
@each $name, $size in map.get($tokens, spacing) {
.m-#{$name} {
margin: $size;
}
}Breakpoints and a map-driven mixin
Breakpoints are a good fit for a map. This builds on the respond mixin idea from the mixins chapter, but takes a name instead of a raw width.
@use 'sass:map';
$breakpoints: (
sm: 36rem,
md: 48rem,
lg: 64rem
);
@mixin respond($name) {
@media (min-width: map.get($breakpoints, $name)) {
@content;
}
}
.nav {
display: block;
@include respond(md) {
display: flex;
}
}The call site now reads respond(md). Changing what "medium" means is a one-line edit in the map.
Failing loudly with a token function
map.get returns null for a missing key and does not raise an error. This gives the most common map bug. When a property value is null, Sass omits the whole declaration from the output. A typo such as map.get($colors, dangr) produces no error and no color property. You only notice when the page looks wrong.
Wrap the lookup in a function that checks the key and stops compilation with @error:
@use 'sass:map';
$colors: (
primary: #3366cc,
danger: #cc3333
);
@function color($name) {
@if not map.has-key($colors, $name) {
@error "Unknown color `#{$name}`. Available: #{map.keys($colors)}";
}
@return map.get($colors, $name);
}
.alert {
color: color(danger);
}If you write color(dangr), the compile stops and prints the message with the list of valid names. This is a small cost for a much better failure.
Changing maps: merge and immutability
Maps are immutable. No function modifies a map in place. map.merge returns a new map, and you decide what to do with it. The usual mistake is calling it and discarding the result:
@use 'sass:map';
$colors: (primary: #3366cc);
// Wrong: the result is thrown away, $colors is unchanged.
$unused: map.merge($colors, (warning: #e0a800));
// Right: assign the new map back to the variable.
$colors: map.merge($colors, (warning: #e0a800));When both maps contain the same key, the second map wins. That makes map.merge a good way to apply overrides to defaults.
With nested maps, map.merge replaces a whole top-level value rather than combining the maps inside it. Merging (colors: (danger: red)) into $tokens would replace the entire colors map. Dart Sass has map.deep-merge for combining nested maps key by key. It has been available since Dart Sass 1.27.0. Use it when you override one nested token and want the rest kept.
Common errors
- Missing parentheses. A map needs parentheses. A one-pair map such as
(primary: #3366cc)must keep them. An empty map is written(). - Printing a map. Using a map as a property value fails with an error like "is not a valid CSS value". Use
map.getor loop with@each. - Silent
null. A bad key removes the declaration without any message. Use a checking function, or@debug map.get($colors, dangr);while you investigate. - Color names as keys. An unquoted
redis parsed as a color value, not a string. A lookup with the quoted string"red"then fails to match. Pick key names that are not CSS color names, or quote keys everywhere. - Mutating by habit. Code from other languages tends to assume
map.mergechanges the map. It does not. - Duplicate keys. Repeating a key in one map literal is a compile error. This usually shows up after copy and paste.
Exercises
Exercise
A stylesheet has $sizes: (sm: 0.5rem, md: 1rem);. The rule .box { padding: map.get($sizes, lg); } compiles without an error. What does the compiled .box contain, and why?
Show answer
It contains no padding declaration, so .box is empty and is usually left out of the output. lg is not a key, so map.get returns null, and Sass drops any declaration whose value is null. A function that checks map.has-key and calls @error would turn this into a compile failure.
Exercise
Write Sass that takes $breakpoints: (sm: 36rem, md: 48rem); and generates a class .hide-sm-up and a class .hide-md-up. Each class must set display: none only at or above its breakpoint.
Show answer
@each $name, $width in $breakpoints { @media (min-width: $width) { .hide-#{$name}-up { display: none; } } }