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