0
0
SASSmarkup~20 mins

Generating utility classes with loops in SASS - Mini Project: Build & Apply

Choose your learning style9 modes available
Generating Utility Classes with Loops in Sass
📖 Scenario: You are creating a simple CSS utility system to quickly add margin spacing to elements. Instead of writing each margin class by hand, you will use Sass loops to generate these classes automatically.
🎯 Goal: Build a Sass stylesheet that uses a @for loop to create margin utility classes named .m-1 through .m-5, each applying margin sizes from 0.5rem to 2.5rem in steps of 0.5rem.
📋 What You'll Learn
Create a Sass list variable called $margins with values 0.5rem, 1rem, 1.5rem, 2rem, and 2.5rem.
Create a variable called $count that stores the number of margin sizes in $margins.
Use a @for loop from 1 through $count to generate classes .m-1 to .m-5.
Each class should set the CSS margin property to the corresponding value from $margins.
The final Sass code should compile to valid CSS with margin utility classes.
💡 Why This Matters
🌍 Real World
Utility CSS classes help developers quickly apply consistent spacing without writing repetitive CSS. Using Sass loops saves time and reduces errors.
💼 Career
Knowing how to automate CSS generation with Sass loops is valuable for front-end developers working on scalable and maintainable stylesheets.
Progress0 / 4 steps
1
Create the margin sizes list
Create a Sass list variable called $margins with these exact values: 0.5rem, 1rem, 1.5rem, 2rem, and 2.5rem.
SASS
Hint

Use parentheses or commas to create a list in Sass. Example: $list: 1rem, 2rem;

2
Create a variable for the count of margin sizes
Create a variable called $count that stores the length of the $margins list using the length() function.
SASS
Hint

Use length($list) to get the number of items in a Sass list.

3
Use a @for loop to generate margin classes
Write a @for loop from 1 through $count that creates classes named .m-1 to .m-5. Inside the loop, set the margin property to the corresponding value from $margins using nth($margins, i).
SASS
Hint

Use @for $i from 1 through $count { ... } and inside use .m-#{$i} for class names.

4
Complete the Sass file for margin utilities
Ensure the Sass code includes the $margins list, the $count variable, and the @for loop that generates the margin utility classes as shown.
SASS
Hint

Make sure all parts are included and the code compiles to CSS with margin classes.