0
0
SASSmarkup~10 mins

@while loop usage in SASS - Browser Rendering Trace

Choose your learning style9 modes available
Render Flow - @while loop usage
[Read @while loop] -> [Check condition] -> [If true: execute block] -> [Update variables] -> [Repeat check] -> [If false: exit loop]
The browser reads the @while loop in Sass, checks the condition, runs the code inside if true, updates variables, and repeats until the condition is false.
Render Steps - 4 Steps
Code Added:$i: 1;
Before
[ ] (empty .boxes container)
After
[ ] (still empty, no boxes yet)
Variable $i is set to 1, but no boxes are created yet.
🔧 Browser Action:Stores variable $i in Sass memory.
Code Sample
Creates three colored boxes with increasing widths using a Sass @while loop.
SASS
<div class="boxes"></div>
SASS
$i: 1;
@while $i <= 3 {
  .boxes {
    & > div:nth-child(#{$i}) {
      width: 5rem * $i;
      height: 5rem;
      background-color: hsl(200, 70%, 50%);
      margin: 0.5rem;
      display: inline-block;
    }
  }
  $i: $i + 1;
}
Render Quiz - 3 Questions
Test your understanding
After the first iteration in render_step 2, what do you see inside the .boxes container?
AOne box with width 5rem
BThree boxes with increasing widths
CNo boxes at all
DOne box with width 15rem
Common Confusions - 2 Topics
Why don't I see any boxes if I forget to increment $i?
Without incrementing $i, the condition $i <= 3 stays true forever, causing an infinite loop in Sass compilation, so no CSS is generated.
💡 Always increase your loop counter inside @while to end the loop.
Why does nth-child(#{$i}) work inside the loop?
Sass replaces #{$i} with the current value of $i, so nth-child(1), nth-child(2), etc. are generated, targeting different elements.
💡 Use #{} to insert variables into selectors dynamically.
Property Reference
Sass @while loop partDescriptionEffect in CSS outputCommon Use
$i: 1;Initialize counter variableNo direct CSS outputStart counting in loop
@while $i <= 3 { ... }Loop runs while condition trueGenerates repeated CSS blocksCreate repetitive styles
$i: $i + 1;Increment counterMoves loop towards endAvoid infinite loops
.boxes > div:nth-child(#{$i})Selects nth child dynamicallyTargets specific elementsStyle multiple elements differently
Concept Snapshot
@while loop runs code while a condition is true. Initialize a counter variable before the loop. Inside the loop, write styles using the counter. Increment the counter to avoid infinite loops. Use #{} to insert variables into selectors. Great for repetitive, patterned CSS generation.