The @each loop helps you repeat styles for each item in a list. It saves time and keeps your code neat.
0
0
@each loop over lists in SASS
Introduction
You want to apply different colors to multiple buttons.
You have a list of font sizes and want to create classes for each size.
You want to create margin or padding classes for a set of spacing values.
You want to style a list of navigation links with different backgrounds.
You want to generate multiple similar styles without writing them one by one.
Syntax
SASS
@each $item in $list {
// styles using $item
}The $item is a variable that holds each value from the list one by one.
The $list is the list of values you want to loop over.
Examples
This creates three classes:
.text-red, .text-green, and .text-blue, each with the matching text color.SASS
$colors: red, green, blue; @each $color in $colors { .text-#{$color} { color: $color; } }
This creates margin classes for each size in the list.
SASS
$sizes: 1rem, 2rem, 3rem; @each $size in $sizes { .margin-#{$size} { margin: $size; } }
If the list is empty, the loop does nothing and no styles are created.
SASS
$empty-list: (); @each $item in $empty-list { .class-#{$item} { color: $item; } } // No output because the list is empty.
Even if the list has only one item, the loop runs once and creates one class.
SASS
$single-item: purple; @each $color in $single-item { .text-#{$color} { color: $color; } }
Sample Program
This code creates three button styles with different background colors from the list. The text color is a lighter shade of the background for good contrast. Each button has padding, rounded corners, and some margin.
SASS
@use "sass:color"; $button-colors: #ff0000, #00ff00, #0000ff; @each $button-color in $button-colors { .btn-#{$button-color} { background-color: $button-color; color: color.scale($button-color, $lightness: 80%); padding: 1rem 2rem; border-radius: 0.5rem; font-weight: bold; display: inline-block; margin: 0.5rem; } }
OutputSuccess
Important Notes
The @each loop runs once for every item in the list.
It is faster and cleaner than writing repetitive CSS for each item.
Remember to use interpolation #{$variable} when using variables inside class names or selectors.
Summary
@each loops over each item in a list to create repeated styles.
Use it to save time and avoid writing the same code many times.
Works well with colors, sizes, or any list of values.