0
0
SASSmarkup~30 mins

@for loop (through vs to) in SASS - Hands-On Comparison

Choose your learning style9 modes available
@for loop (through vs to) in Sass
📖 Scenario: You are creating a simple color palette for a website. You want to generate CSS classes for background colors using Sass loops.
🎯 Goal: Build a Sass stylesheet that uses @for loops with both through and to keywords to generate CSS classes for background colors with numbered suffixes.
📋 What You'll Learn
Create a Sass list variable with exactly 5 color hex codes.
Create a variable color-count set to the number 5.
Use an @for loop with through to generate CSS classes named .bg-color-1 through .bg-color-5 with background colors from the list.
Use a second @for loop with to to generate CSS classes named .text-color-1 through .text-color-4 with text colors from the list.
💡 Why This Matters
🌍 Real World
Using Sass loops helps you write less repetitive CSS code when you have many similar styles, like color palettes or spacing scales.
💼 Career
Front-end developers often use Sass loops to maintain scalable and maintainable stylesheets, saving time and reducing errors.
Progress0 / 4 steps
1
Create a Sass list of colors
Create a Sass list variable called $colors with these exact hex color values: #ff0000, #00ff00, #0000ff, #ffff00, #ff00ff.
SASS
Hint

Use parentheses or commas to create a list in Sass. Example: $list: val1, val2, val3;

2
Create a variable for color count
Create a Sass variable called $color-count and set it to the number 5.
SASS
Hint

Assign a number to a variable using $variable-name: value; syntax.

3
Use @for loop with through to create background color classes
Write an @for loop using through with the loop variable $i from 1 through $color-count. Inside the loop, create CSS classes named .bg-color-#{$i} that set background-color to the $ith color from the $colors list.
SASS
Hint

Use @for $i from 1 through $color-count { ... } and nth($colors, $i) to get the color.

4
Use @for loop with to to create text color classes
Write a second @for loop using to with the loop variable $i from 1 to $color-count. Inside the loop, create CSS classes named .text-color-#{$i} that set color to the $ith color from the $colors list.
SASS
Hint

Remember that to excludes the last number, so it loops from 1 up to 4 if $color-count is 5.