@each Loops
Iterate over lists and maps to generate rules.
Syntax
@each $item in $list { } @each $k, $v in $map { }@each loops over every item in a list or every pair in a map, generating a block for each. This is the most common way to turn design tokens into utility classes or modifier rules.
Destructuring
When looping a map, you get the key and value together: @each $key, $value in $map. You can also destructure nested lists.
Example
$colors: (
'primary': #CC6699,
'accent': #6699CC,
'danger': #d9534f,
);
@each $name, $color in $colors {
.text-#{$name} { color: $color; }
.bg-#{$name} { background: $color; }
}
/* .text-primary { color: #CC6699; }
.bg-primary { background: #CC6699; } ...and so on */When to use it
- A developer loops over a list of status colors to generate .badge-success, .badge-warning, and .badge-error with a single @each block.
- A design system loops over a spacing scale map to emit --space-1 through --space-8 CSS custom properties from one concise rule.
- A team generates responsive display utilities by nesting @each loops over both a breakpoint list and a display value list.
More examples
@each over a list
Iterates over four status names to generate matching badge variant classes, each referencing a CSS custom property by interpolated name.
$statuses: success, warning, error, info;
@each $s in $statuses {
.badge-#{$s} {
@extend %badge-base;
border-left: 3px solid var(--color-#{$s});
}
}@each over a map
Destructures key-value pairs from a spacing map to emit a set of CSS custom property declarations in one @each loop.
@use 'sass:map';
$spacing: (1: 0.25rem, 2: 0.5rem, 4: 1rem, 8: 2rem, 16: 4rem);
:root {
@each $key, $value in $spacing {
--space-#{$key}: #{$value};
}
}Nested @each for utilities
Nests two @each loops to generate responsive text-alignment utilities like .md:text-center for every breakpoint and alignment combination.
$bps: (sm: 640px, md: 768px, lg: 1024px);
$aligns: left, center, right;
@each $bp, $width in $bps {
@media (min-width: $width) {
@each $a in $aligns {
.#{$bp}\:text-#{$a} { text-align: $a; }
}
}
}
Discussion