0
0
SASSmarkup~3 mins

Why @each loop over lists 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 are styling a website with multiple buttons, each needing a different background color. You write CSS rules for each button color one by one, repeating similar code again and again.

The Problem

If you want to add or change a color, you must find and update every single rule manually. This takes a lot of time and can cause mistakes or inconsistent styles.

The Solution

The @each loop in Sass lets you list all your colors once and automatically create styles for each. You write less code and can easily add or remove colors without repeating yourself.

Before vs After
Before
.btn-red { background: red; }
.btn-blue { background: blue; }
.btn-green { background: green; }
After
@each $color in (red, blue, green) {
  .btn-#{$color} {
    background: $color;
  }
}
What It Enables

You can quickly generate many similar styles from a list, making your CSS easier to maintain and update.

Real Life Example

When building a theme with multiple color options, you can define all colors in a list and use @each to create button styles, link colors, or backgrounds automatically.

Key Takeaways

@each loops over a list of items to repeat code for each.

It saves time and reduces errors by avoiding repeated manual code.

It makes your styles flexible and easy to update.