liveBook · Manning

Sass @each at-rule

As explained in Tiny CSS Projects

The Sass @each at-rule iterates over items in a list or map and evaluates a block for each item.

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

How Tiny CSS Projects covers it

How deep it goes
Explains map iteration, loop variables, interpolation, debugging, and compiled CSS output without deeper Sass implementation details.
Examples
Uses success, warning, and error callouts to demonstrate map iteration, terminal debugging, and generated CSS.
What you can do after
Build it from scratch by looping over Sass lists or maps to generate repeated selectors and property values.
How it connects
Connects @each with Sass maps, variables, interpolation, nesting, @extend, and @debug.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Tiny CSS Projects. The section links point to the parts of the book it draws on.