Sass Looping Methods and Iteration
Basic Structure of Loop Statements
Sass loop statements are implemented using the @each keyword, allowing developers to generate repeated style definitions based on variables. For example, you can declare a variable with @each and then repeat its values within the loop:
$colors = (
'red',
'blue',
'green'
)
@each $color in $colors {
.btn-#{$color} {
background-color: $color;
}
}
Loop Variables and Nesting
Loop variables (such as $color) can be used directly to generate style definitions and support nested loops. For example, multiple class names or style properties can be generated simultaneously:
@each $color in $colors {
.btn-#{$color} {
background-color: $color;
border-color: #ddd;
}
}
Iteration Mechanism and Control Flow
Sass's loop mechanism supports break and continue statements to control the execution flow of loops. For example, a loop can be terminated when a specific condition is detected, or certain iterations can be skipped:
@each $color in $colors {
.btn-#{$color} {
background-color: $color;
@if $color == 'red' {
border-width: 2px;
}
}
}
Loop Scope and Termination Conditions
The scope of Sass loops is typically based on the order of variable values, but dynamic control over the loop range can be achieved using the @for keyword. For example, a specific number of class names can be generated:
@for $i from 1 to 3 {
.btn-#{$i} {
background-color: hsl(#{$i * 120}, 100%, 50%);
}
}
Nested Loops and Complex Logic
Sass supports nested loops, which can implement complex style generation logic. For example, multiple class names can be generated simultaneously while applying the same styles:
@for $i from 1 to 3 {
@for $j from 1 to 2 {
.btn-#{$i}-#{$j} {
background-color: hsl(#{$i * 120}, 100%, 50%);
}
}
}
Practical Application Scenarios
Loop statements are widely used to generate repeated style definitions, such as for components like buttons or cards. By reasonably utilizing variables and nested loops, the maintainability and efficiency of code can be significantly improved. For example, dynamically generating multi-color button styles:
$colors = (
'red',
'blue',
'green'
)
@each $color in $colors {
.btn-#{$color} {
background-color: $color;
border-radius: 4px;
@media (max-width: 768px) {
font-size: 14px;
}
}
}