Maps

Store key/value pairs — perfect for design tokens.

Syntax@use 'sass:map'; map.get($map, 'key')

A map associates keys with values, written as (key: value, key: value). Maps are the backbone of scalable Sass: use them for color palettes, spacing scales, and breakpoints.

Reading maps

Use the sass:map module: map.get() fetches a value by key, map.has-key() checks for a key, and map.keys() lists all keys.

Example

Example · css
@use 'sass:map';

$colors: (
  'primary': #CC6699,
  'accent':  #6699CC,
  'text':    #333333,
);

.button {
  background: map.get($colors, 'primary');
  color: white;
}
.link {
  color: map.get($colors, 'accent');
}

When to use it

  • A design system stores all brand colors as a Sass map keyed by semantic name, then uses map.get() to apply the right color in each component.
  • A developer keeps all z-index layers in a map to prevent collisions and uses a lookup function everywhere instead of scattered magic numbers.
  • A team defines all breakpoints in a single map so every responsive mixin reads from the same source of truth, making global changes a one-line edit.

More examples

Defining and reading a color map

Stores semantic color tokens in a map and retrieves the danger color by key for the danger button variant.

Example · css
@use 'sass:map';

$colors: (
  primary:   #2563eb,
  success:   #16a34a,
  danger:    #dc2626,
  neutral:   #6b7280
);

.btn-danger {
  background: map.get($colors, danger);
}

Looping over a map

Destructures each key-value pair from the map in a loop to generate text and background utility classes for every color.

Example · css
@use 'sass:map';

$colors: (primary: #2563eb, success: #16a34a, danger: #dc2626);

@each $name, $value in $colors {
  .text-#{$name} { color: $value; }
  .bg-#{$name}   { background: $value; }
}

Z-index map with lookup function

Centralizes all z-index values in a map and wraps map.get() in a small function so call sites are readable and typo-safe.

Example · css
@use 'sass:map';

$z-layers: (base: 0, dropdown: 100, modal: 200, toast: 300);

@function z($layer) {
  @return map.get($z-layers, $layer);
}

.modal   { z-index: z(modal); }
.tooltip { z-index: z(toast); }

Discussion

  • Be the first to comment on this lesson.