SyntaxStudy
Sign Up
SASS / SCSS @each for Iterating Lists and Maps
SASS / SCSS Beginner 1 min read

@each for Iterating Lists and Maps

The `@each` directive iterates over items in a SASS list or the key-value pairs of a SASS map. The basic syntax `@each $item in $list` makes the current item available as `$item` inside the block. For maps, the destructuring syntax `@each $key, $value in $map` provides both the key and value on each iteration, making `@each` over maps extremely expressive. Iterating over maps with `@each` is one of the most powerful patterns in SASS for generating systematic utility classes. A single map of theme colors, sizing values, or breakpoints combined with an `@each` loop can generate dozens of utility classes from a handful of configuration lines. Changing a map value automatically updates all generated classes. `@each` also supports multiple assignment for lists of lists (a two-dimensional list). If the list items are themselves lists, you can write `@each $a, $b, $c in $pairs` to destructure each sub-list on each iteration. This pattern is useful for pairing related values — such as a class name with a color — when a full map would be too heavyweight.
Example
// ── @each over a simple list ──────────────────────────────────────────────────

$sides: top, right, bottom, left;

@each $side in $sides {
    .border-#{$side}-0 { border-#{$side}: none; }
    .border-#{$side}   { border-#{$side}: 1px solid #e0e0e0; }
}

// ── @each over a map — theme color utilities ──────────────────────────────────

$theme-colors: (
    'primary'  : #3498db,
    'secondary': #2ecc71,
    'danger'   : #e74c3c,
    'warning'  : #f39c12,
    'info'     : #17a2b8,
    'dark'     : #2c3e50,
    'light'    : #ecf0f1
);

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

    .btn-#{$name} {
        background: $color;
        color     : if(lightness($color) > 60%, #333, #fff);
        padding   : 0.5rem 1rem;
        border    : none;
        border-radius: 4px;
        cursor    : pointer;
        &:hover { background: darken($color, 10%); }
    }
}

// ── @each with list-of-lists (multiple assignment) ────────────────────────────

$icon-sizes: (sm 16px, md 24px, lg 32px, xl 48px);

@each $label, $size in $icon-sizes {
    .icon-#{$label} {
        width : $size;
        height: $size;
        font-size: $size;
    }
}