Sass’s @each at-rule repeats a block for every item in a list or map. With a map, variables receive each key and value, making one rule pattern generate several related selectors. section 12.5
A map-based loop follows this pattern:
- Create a map of callout types and color values: $callouts: (success: $success, warning: $warning, error: $error). section 12.5
- Declare @each $type, $color in $callouts; $type receives the key, and $color receives its value. section 12.5
- Place the rules to generate inside the loop’s braces, using interpolation when a variable must become part of a selector or string. section 12.5
Generate colored callouts
A loop can extend a shared .callout rule, create a class from each type, apply its color, and add a label: @each $type, $color in $callouts { .#{$type} { @extend .callout; border-color: $color; &::before { content: "#{$type}: "; text-transform: capitalize; } } }. The generated CSS contains separate .success, .warning, and .error rules with their corresponding borders and labels. section 12.5
Listing 12.22 Adding to the loop (SCSS)
.callout {
border: solid 1px;
border-radius: 4px;
padding: .5rem 1rem;
}
$callouts: (success: $success, warning: $warning, error: $error);
@each $type, $color in $callouts {
@debug $type, $color;
.#{$type} { #1
@extend .callout;
border-color: $color;
&::before {
content: "#{$type}: "; #2
text-transform: capitalize;
}
}
}
Inspect the complete SCSS loop, including interpolation, @extend, border-color, and generated labels. section 12.5
@debug can print the current key and value while testing a loop. Its output appears in the local terminal rather than the browser console, helping verify map values before completing the generated rules. section 12.5
