0
0
SASSmarkup~3 mins

Why @while loop usage in SASS? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

Discover how a simple loop can save you hours of tedious CSS writing!

The Scenario

Imagine you want to create a set of buttons with different shades of blue, each slightly darker than the last. You write CSS for each button color by hand, repeating similar code over and over.

The Problem

This manual method is slow and boring. If you want to change the number of buttons or the shade steps, you must rewrite or copy-paste many lines, risking mistakes and inconsistencies.

The Solution

The @while loop in Sass lets you write one block of code that repeats automatically. It counts and changes values for you, so you only write the pattern once.

Before vs After
Before
.btn-1 { background: blue; }  .btn-2 { background: darkblue; }  .btn-3 { background: navy; }
After
$i: 1; @while $i <= 3 {  .btn-#{$i} { background: darken(blue, $i * 10%); }  $i: $i + 1; }
What It Enables

You can create many style variations quickly and change them easily by adjusting just a few values.

Real Life Example

Designers often need multiple button sizes or colors for a website. Using @while loops, they generate all these styles with less code and fewer errors.

Key Takeaways

Writing repetitive styles by hand is slow and error-prone.

@while loops automate repetition in Sass.

This saves time and makes style changes easier and safer.