SASS Loops
Syntax
SASS supports different types of loops like @for, @while etc. Here is the basic syntax for a @for loop in SASS:
@for $var from start through end {
// statements to be executed
}
$var
: Loop variable, which will take values from the start to the end.start
: Starting value of a loop variable.end
: Ending value of a loop variable.
Example
@for $i from 1 through 5 {
.card-#{$i} {
width: calc(20% * #{$i});
}
}
Output
.card-1 {
width: calc(20% * 1);
}
.card-2 {
width: calc(20% * 2);
}
.card-3 {
width: calc(20% * 3);
}
.card-4 {
width: calc(20% * 4);
}
.card-5 {
width: calc(20% * 5);
}
Explanation
In the example above, we are using a @for
loop to generate CSS for a set of classes that are based on a numeric value. Here we are starting from 1
and ending at 5
. For each iteration, .card-
is being concatenated with the index number generated in #{$i}
using String interpolation. The width of each card class is calculated using calc()
function.
Use
SASS loops are useful when we want to generate similar CSS blocks with incremental or calculated values. It saves developers time and effort instead of hardcoding static values in CSS.
Important Points
- Unlike other programming languages, SASS does not support nested loops.
- Variables increment in steps of 1 by default, but we can set steps to any desired value.
Summary
SASS loops allow developers to generate a group of CSS rules using a single block of code and reduce the repetition of code. The @for
loop is used to execute a block of code for a specified number of times. It provides flexibility to generate incremental or calculated numeric values used in CSS properties.