The clinical definition of the @while
directive is; the @while
directive takes an expression and while the expression is true, the code block within the @while
declaration will be implemented.
Let's look at a textbook example:
$class-name: span !default;
$start-width: 25%;
$i: 4;
@while $i > 0 {
.#{$class-name}-#{$i} {
width: $start-width * $i;
}
$i: $i - 1;
}
The above code will compile to:
.span-4 {
width: 100%;
}
.span-3 {
width: 75%;
}
.span-2 {
width: 50%;
}
.span-1 {
width: 25%;
}
The key with this directive is that you need to set a manual iterator for this to work, for example $i: $i - 1;
. This iterator will take the original value of $i
and then subtract 1
with each loop. The directive itself is stating, @while $i > 0
keep executing the loop. Pretty simple, right?