Design Tokens with Maps
Centralize colors, spacing, and type scale in maps.
$tokens: (key: value); token('key')Design tokens are the named values that define your visual language: colors, spacing steps, font sizes, breakpoints. Storing them in maps gives you a single source of truth you can loop over.
Combine a token map with a small accessor function so the rest of your code reads tokens by name, with a helpful error if a name is misspelled.
Example
@use 'sass:map';
$space: ('sm': 8px, 'md': 16px, 'lg': 24px);
@function space($key) {
@if not map.has-key($space, $key) {
@error "Unknown space token: #{$key}.";
}
@return map.get($space, $key);
}
.card {
padding: space('md');
margin-bottom: space('lg');
}When to use it
- A design system stores all spacing, color, and typography values in a central Sass map so changing $space-unit: 8px to 10px updates every component at once.
- A developer uses nested maps for color tokens (grouped by semantic role) and loops over them to emit CSS custom properties in :root.
- A team sources tokens from a single _tokens.scss file and @forward-s it through their abstracts index, ensuring every partial reads from the same source of truth.
More examples
Color tokens in a map
Organizes color tokens into a nested map grouped by semantic category, then retrieves the primary brand color with nested map.get() calls.
@use 'sass:map';
$colors: (
brand: (
primary: #2563eb,
secondary: #7c3aed
),
feedback: (
success: #16a34a,
error: #dc2626
)
);
$primary: map.get(map.get($colors, brand), primary);Emitting tokens as CSS custom properties
Loops over both the spacing and color maps to emit all design tokens as CSS custom properties in one concise :root block.
@use 'sass:map';
$spacing: (1: 0.25rem, 2: 0.5rem, 4: 1rem, 8: 2rem);
$colors: (primary: #2563eb, success: #16a34a);
:root {
@each $k, $v in $spacing { --space-#{$k}: #{$v}; }
@each $k, $v in $colors { --color-#{$k}: #{$v}; }
}Token access helper function
Wraps map.get() in a token() function that validates keys at compile time, catching typos before they silently produce invalid CSS.
@use 'sass:map';
$tokens: (space-4: 1rem, space-8: 2rem, color-primary: #2563eb);
@function token($key) {
@if not map.has-key($tokens, $key) {
@error 'Unknown token: #{$key}';
}
@return map.get($tokens, $key);
}
.btn { padding: token(space-4); background: token(color-primary); }
Discussion