0
0
SASSmarkup~5 mins

@while loop usage in SASS

Choose your learning style9 modes available
Introduction

The @while loop helps you repeat a set of styles as long as a condition is true. It saves time and keeps your code neat.

When you want to create multiple similar CSS classes with incremental changes.
When you need to generate a series of styles based on a number count.
When you want to avoid writing repetitive code for things like spacing or colors.
When you want to automate style variations like button sizes or grid columns.
Syntax
SASS
@while <condition> {
  // styles or code here
  // update condition variable
}

The @while loop runs as long as the condition is true.

Make sure to update the variable inside the loop to avoid infinite loops.

Examples
This creates three boxes with increasing widths: 100px, 200px, and 300px.
SASS
$i: 1;
@while $i <= 3 {
  .box-#{$i} {
    width: 100px * $i;
    height: 100px;
    background: blue;
  }
  $i: $i + 1;
}
This creates five classes with decreasing margin sizes.
SASS
$count: 5;
@while $count > 0 {
  .item-#{$count} {
    margin-bottom: 10px * $count;
  }
  $count: $count - 1;
}
Sample Program

This SASS code creates four circle classes with increasing sizes. Each circle will be bigger than the last.

SASS
@charset "UTF-8";

$i: 1;
@while $i <= 4 {
  .circle-#{$i} {
    width: 2rem * $i;
    height: 2rem * $i;
    background-color: teal;
    border-radius: 50%;
    margin: 0.5rem;
    display: inline-block;
  }
  $i: $i + 1;
}
OutputSuccess
Important Notes

Always update the loop variable inside the @while block to prevent infinite loops.

You can use @while loops to generate repetitive styles dynamically, which keeps your CSS smaller and easier to maintain.

Summary

@while loops repeat styles while a condition is true.

They help avoid writing the same code many times.

Remember to change the loop variable inside the loop to stop it eventually.