Generate Styles with @each

The @each directive iterates over a list or map. It is ideal for generating classes from named tokens because each iteration exposes a value or a key-value pair.

For a map of button variants, a loop can generate a class for every supported variant. For a spacing map, a loop can generate utilities for approved spacing tokens.

Generated utilities should be intentionally scoped. A loop that creates hundreds of selectors may produce unnecessary CSS if only a few classes are used. Consider whether a small set of reusable component styles would be more appropriate.

Generate Button Variants
$button-colors: (
  primary: #5b5bd6,
  success: #218838,
  danger: #c62828
);

@each $name, $color in $button-colors {
  .button--#{$name} {
    background-color: $color;
    color: white;
  }
}
💡 The loop iterates through each map entry. Interpolation inserts the key into the selector, and the corresponding color becomes the background value. The resulting stylesheet contains .button--primary, .button--success, and .button--danger.
Knowledge Check

Which directive is the natural choice for iterating through a map of named button variants?