0
0
SASSmarkup~3 mins

Why @each loop over maps in SASS? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

Discover how a simple loop can save you hours of repetitive styling work!

The Scenario

Imagine you have a list of colors and their shades stored in a map, and you want to create CSS classes for each shade manually.

The Problem

Writing each class by hand is slow and boring. If you add or change a color, you must update every class manually, risking mistakes and wasting time.

The Solution

The @each loop over maps lets you automatically create styles for each color and shade, so you write less code and avoid errors.

Before vs After
Before
.red-light { color: #f88; }
.red-dark { color: #800; }
After
$colors: (red-light: #f88, red-dark: #800);
@each $name, $color in $colors {
  .#{$name} { color: $color; }
}
What It Enables

You can generate many CSS rules dynamically from data, making your stylesheets easier to maintain and update.

Real Life Example

When building a website theme with multiple color options, you can define all colors in a map and create matching classes automatically.

Key Takeaways

Manually writing styles for each map item is slow and error-prone.

@each loops over maps automate style generation.

This makes your CSS easier to update and scale.