📅  最后修改于: 2023-12-03 15:15:09.944000             🧑  作者: Mango
Sass is a preprocessor scripting language that is compiled into CSS. The for
loop in Sass is an extremely powerful feature that allows developers to create complex CSS with a few lines of code.
for
LoopThe for
loop in Sass is used to loop through a set of values and create styles based on it. There are two ways to use the for
loop in Sass.
@for
RuleThe @for
rule is used to loop through a set of values and create styles based on it. It follows the following syntax:
@for $variable from <start> through <end> {
// Styles to be applied
}
Here, $variable
is a variable that will hold the current value of the loop. <start>
is the starting value of the loop and <end>
is the ending value of the loop. The loop will run from <start>
to <end>
.
@for $i from 1 through 5 {
.box-#{$i} {
width: 10px * $i;
}
}
This will create the following CSS:
.box-1 {
width: 10px;
}
.box-2 {
width: 20px;
}
.box-3 {
width: 30px;
}
.box-4 {
width: 40px;
}
.box-5 {
width: 50px;
}
@each
RuleThe @each
rule is used to loop through a list and create styles based on it. The list can contain any type of values, including numbers, strings, and CSS selectors. It follows the following syntax:
@each $variable in <list> {
// Styles to be applied
}
Here, $variable
is a variable that will hold the current value of the loop. <list>
is the list that needs to be looped through.
@each $color in red, green, blue {
.color-#{$color} {
color: $color;
}
}
This will create the following CSS:
.color-red {
color: red;
}
.color-green {
color: green;
}
.color-blue {
color: blue;
}
The for
loop in Sass is an extremely powerful feature that can be used to create complex CSS with a few lines of code. The @for
and @each
rules are the two ways to use the for
loop in Sass.