0
0
SASSmarkup~3 mins

@for loop (through vs to) in SASS - When to Use Which

Choose your learning style9 modes available
The Big Idea

Discover how a tiny change in your loop can save hours of repetitive work!

The Scenario

Imagine you want to create 10 colored boxes on a webpage. You write the CSS for each box one by one, changing colors and sizes manually.

The Problem

If you decide to add more boxes or change the number, you must rewrite or copy-paste many lines. This wastes time and can cause mistakes like missing a box or repeating styles.

The Solution

The @for loop in Sass lets you write one block of code that repeats automatically. Using through or to, you control if the loop includes the last number or stops before it, making your code cleaner and easier to update.

Before vs After
Before
.box1 { color: red; } .box2 { color: orange; } .box3 { color: yellow; }
After
@for $i from 1 through 3 { .box#{$i} { color: nth((red, orange, yellow), $i); } }
What It Enables

You can quickly create many similar styles with fewer lines and change the number of items by editing just one place.

Real Life Example

When designing a navigation menu with multiple items, you can style each item with a loop instead of writing separate styles for each link.

Key Takeaways

@for loops automate repetitive CSS tasks.

through includes the last number; to stops before it.

Loops save time and reduce errors when scaling styles.