0
0
SASSmarkup~10 mins

@for loop (through vs to) in SASS - Browser Rendering Compared

Choose your learning style9 modes available
Render Flow - @for loop (through vs to)
[Read @for loop syntax] -> [Determine loop range] -> [Iterate from start to end] -> [Generate CSS rules for each iteration] -> [Compile final CSS]
The Sass compiler reads the @for loop, decides the range based on 'through' or 'to', runs the loop for each number, and outputs CSS rules accordingly.
Render Steps - 3 Steps
Code Added:@for $i from 1 through 3 { .box#{$i} { width: 5rem * $i; height: 5rem; background-color: hsl(200, 70%, 50%); margin-bottom: 1rem; } }
Before
[ ]
[ ]
[ ]
After
[■■■■■_____]
[■■■■■■■■__]
[■■■■■■■■■■■]
Three boxes appear stacked vertically with widths increasing from 5rem to 15rem because 'through' includes 3.
🔧 Browser Action:Generates CSS for .box1, .box2, .box3; browser lays out boxes with specified widths and heights.
Code Sample
Three boxes with increasing widths are created; using 'through' includes the last number, 'to' excludes it.
SASS
<div class="box1"></div>
<div class="box2"></div>
<div class="box3"></div>
SASS
@for $i from 1 through 3 {
  .box#{$i} {
    width: 5rem * $i;
    height: 5rem;
    background-color: hsl(200, 70%, 50%);
    margin-bottom: 1rem;
  }
}

/* Change 'through' to 'to' changes loop range */
Render Quiz - 3 Questions
Test your understanding
After applying the @for loop with 'through', how many boxes have visible width styles?
ATwo boxes with increasing widths
BThree boxes all the same width
CThree boxes with increasing widths
DNo boxes have width styles
Common Confusions - 2 Topics
Why does my loop skip the last number when I use 'to'?
'to' means the loop stops before the last number, so it excludes it. Use 'through' if you want to include the last number. See render_step 2 where changing 'through' to 'to' removes the last box.
💡 Remember: 'through' includes the end number; 'to' stops before it.
Why does my third box disappear when I use 'to'?
Because the loop only runs up to one less than the end number, no CSS is generated for the third box, so it has no size or color. See render_step 2 for the visual difference.
💡 Check how many iterations your loop runs to match your HTML elements.
Property Reference
PropertyValueEffect on LoopVisual ResultCommon Use
@forfrom 1 through 3Includes last numberGenerates styles for 1, 2, 3When you want to include the end number
@forfrom 1 to 3Excludes last numberGenerates styles for 1, 2 onlyWhen you want to exclude the end number
width5rem * $iN/ABoxes grow wider each iterationCreate size variations
margin-bottom1remN/AAdds vertical spacingSeparate stacked elements visually
Concept Snapshot
@for loop in Sass runs a block multiple times. Use 'from X through Y' to include Y in the loop. Use 'from X to Y' to exclude Y. Loop variable can control styles like width. Changing 'through' vs 'to' changes how many times styles are generated.