Discover how a tiny change in your loop can save hours of repetitive work!
@for loop (through vs to) in SASS - When to Use Which
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.
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 @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.
.box1 { color: red; } .box2 { color: orange; } .box3 { color: yellow; }@for $i from 1 through 3 { .box#{$i} { color: nth((red, orange, yellow), $i); } }
You can quickly create many similar styles with fewer lines and change the number of items by editing just one place.
When designing a navigation menu with multiple items, you can style each item with a loop instead of writing separate styles for each link.
@for loops automate repetitive CSS tasks.
through includes the last number; to stops before it.
Loops save time and reduce errors when scaling styles.