The @each directive allows you to iterate through any list or map. It takes the form of @each $var or <list or map> {}
where $var
can be any variable name and <list or map>
can be anything that returns a list or map.
In the following example, the loop will iterate through the $authors
list assigning each item to $author
, process its block of styles using that value of $author
, and proceed to the next item in the list.
SCSS Example
$authors: "adam", "steve", "john";
@each $author in $authors {
.photo-#{$author} {
background: image-url("avatars/#{$author}.png") no-repeat
}
}
CSS Output
.photo-adam {
background: image-url("avatars/adam.png") no-repeat;
}
.photo-steve {
background: image-url("avatars/steve.png") no-repeat;
}
.photo-john {
background: image-url("avatars/john.png") no-repeat;
}
Multiple assignment allows you to gain easy access to all of the variables by declaring multiple variables in the @each
directive.
Nested Lists
To have easy access to all the nested elements, you may declare separate variables to match each nested element. Be sure you have the correct amount of variables and nested elements. In the following example, an each loop is iterating through a list of three elements each of which contains three elements nested. Having the wrong amount of declared variables will result in a compiler error.
@each $animal, $color, $cursor in (puma, black, default),
(sea-slug, blue, pointer),
(egret, white, move) {
.#{$animal}-icon {
background-image: url('/images/#{$animal}.png');
border: 2px solid $color;
cursor: $cursor;
}
}
Maps
Multiple assignment works for Maps as well but is limited to only two variables, a variable to access the key and a variable to access the value. The names $key
and $value
are arbitary in the following example:
@each $key, $value in ('first': 1, 'second': 2, 'third': 3) {
.order-#{$key} {
order: $value;
}
}