Sass @each Rule (original) (raw)
Last Updated : 18 Aug, 2024
The ****@each rule** is used to emit styles or evaluate codes for each element of a list or each pair of a map. It is most advantageous for repeating styles that have a few differences in them. The section is evaluated for every element of the list or pair of the map which has been assigned to the provided variable name.
**Syntax:
@each in {
. . .
}
**Example: This example shows the use of the SASS @each rule.
css `
$sizes: 20px, 30px, 100px;
@each sizeinsize in sizeinsizes { .gfg-#{$size} { font-size: $size; height: $size; width: $size; } }
`
**Output:
.gfg-20px {
font-size: 20px;
height: 20px;
width: 20px;
}
.gfg-30px {
font-size: 30px;
height: 30px;
width: 30px;
}
.gfg-100px {
font-size: 100px;
height: 100px;
width: 100px;
}
The ****@each** rule can also be used for maps, by iterating over every key/value pair of the map.
**Syntax:
@each , in {
. . .
}
**Example: In this example, the key is assigned to the first variable name, and the element is assigned to the second.
css `
$colors: ( arial: black, sans-serif: green, algerian: gray );
@each $name, fontinfont in fontincolors { .font-#{$name}:before { background-color: white; font-family: $name; color: $font; } }
`
**Output:
.font-arial:before {
background-color: white;
font-family: arial;
color: black;
}
.font-sans-serif:before {
background-color: white;
font-family: sans-serif;
color: green;
}
.font-algerian:before {
background-color: white;
font-family: algerian;
color: gray;
}
**Destructuring: The @each rule can also automatically assign variables in list of lists to each of the values in the inner list. As the variables match the structure of the inner lists, it is called as destructuring. Each variable name is assigned to the value at their corresponding position in the list, or null if the list doesn’t have enough values.
**Syntax:
@each <variables...> in {
. . .
}
**Example: In this example, the key is assigned to the first variable name, and the element is assigned to the second.
css `
$colors: arial black 10px, sans-serif green 12px, algerian gray 20px;
@each $name, $font, sizeinsize in sizeincolors { .font-#{$name}:before { background-color: white; font-family: $name; color: $font; font-size: $size; } }
`
**Output:
.font-arial:before {
background-color: white;
font-family: arial;
color: black;
font-size: 10px;
}
.font-sans-serif:before {
background-color: white;
font-family: sans-serif;
color: green;
font-size: 12px;
}
.font-algerian:before {
background-color: white;
font-family: algerian;
color: gray;
font-size: 20px;
}