For each loop is similar to a for loop in SassScript.
You can also use @each rule to iterate over each key and value pair in a map.
Syntax
@each $key, $value in $list {
...
}
Can you use $value first and then $key second?
NO.
SassScript will assign the value of key to the first variable and value to the second variable.
I have used $key just for simplicity purposes. It can be any variable.
Example
$widths: ("full": "100%", "half": "50%");
@each $width, $percent in $widths {
.img-#{$width}{
width: $percent;
}
}
The code above will compile into this CSS:
.img-full{
width: 100%;
}
.img-half{
width: 50%;
}
What about a list of lists?
SassScript calls it destructuring when you use @each rule with a list of lists.
When you use @each rule with a list of lists, it automatically assigns values from the list to each variables specified.
The order is important since the first variable will be assigned the first value and so on.
What if the inner list is missing values?
Then a null value will be assigned to the variable in place.
Example
$sizes:
"full" "100%" "auto",
"half" "50%" "300px";
@each $size, $width, $height in $sizes {
.img-#{$size}{
width: $width;
height: $height;
}
}
The code above will be compiled into this CSS:
.img-full{
width: 100%;
height: auto;
}
.img-half{
width: 50%;
height: 300px;
}
forEach loop rules sass