@each
The @each
directive usually has the form @each $var in <list or map>
. $var
can be any variable name, like $length
or $name
, and <list or map>
is a SassScript expression that returns a list or a map.
The @each
rule sets $var
to each item in the list or map, then outputs the styles it contains using that value of $var
. For example:
@each $animal in puma, sea-slug, egret, salamander {
.#{$animal}-icon {
background-image: url('/images/#{$animal}.png');
}
}
is compiled to:
.puma-icon {
background-image: url('/images/puma.png'); }
.sea-slug-icon {
background-image: url('/images/sea-slug.png'); }
.egret-icon {
background-image: url('/images/egret.png'); }
.salamander-icon {
background-image: url('/images/salamander.png'); }
Multiple Assignment
The @each
directive can also use multiple variables, as in @each $var1, $var2, ... in <list>
. If <list>
is a list of lists, each element of the sub-lists is assigned to the respective variable. For example:
@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;
}
}
is compiled to:
.puma-icon {
background-image: url('/images/puma.png');
border: 2px solid black;
cursor: default; }
.sea-slug-icon {
background-image: url('/images/sea-slug.png');
border: 2px solid blue;
cursor: pointer; }
.egret-icon {
background-image: url('/images/egret.png');
border: 2px solid white;
cursor: move; }
Since maps are treated as lists of pairs, multiple assignment works with them as well. For example:
@each $header, $size in (h1: 2em, h2: 1.5em, h3: 1.2em) {
#{$header} {
font-size: $size;
}
}
is compiled to:
h1 {
font-size: 2em; }
h2 {
font-size: 1.5em; }
h3 {
font-size: 1.2em; }
Please login to continue.