Sass For and While Loops
Generate a bounded pair of layout helpers.
How it works
@for is useful when the number of steps is known. Through includes its upper endpoint, whereas to excludes it. @while repeats while its condition stays true and therefore needs an update that can end the loop. Both run at build time. The small example uses each once so you can compare their stopping rules without producing a large utility library.
Run the code
Use Dart Sass 1.107.0 in a separate learning folder. Install Node.js, then run npm install --save-dev --save-exact sass@1.107.0. Save every file below with its shown path. Run npx sass for-while.scss for-while.css --no-source-map from that folder. Browsers receive compiled CSS, not Sass.
The existing Sass playground uses legacy LibSass 3.6.2 and cannot run modern modules. The compiled CSS preview uses the isolated HTML/CSS editor; it does not compile Sass online. Preloading does not execute the preview. Apache, MySQL and PHP are not required.
Example
for-while.scss
Download for-while.scss — save at the shown relative path.
@for $n from 1 through 2 {
.cols-#{$n} {
grid-template-columns: repeat($n, 1fr);
}
}
$n: 1;
@while $n < 3 {
.gap-#{$n} {
gap: $n * 4px;
}
$n: $n + 1;
}
Expected CSS
.cols-1 {
grid-template-columns: repeat(1, 1fr);
}
.cols-2 {
grid-template-columns: repeat(2, 1fr);
}
.gap-1 {
gap: 4px;
}
.gap-2 {
gap: 8px;
}
The for loop emits two column patterns. The while loop increments n after each emitted rule and stops before three. Prefer the simpler for form for fixed counts; use while only when the next step depends on a changing calculation.
Preview compiled CSS — choose Run code. Change and compile Sass locally first.
Technical reference: official Sass documentation. Original fictional film-club examples; no booking service is provided.