Sass Control Directives: Logic in Your Stylesheets
Sass control directives bring programming logic—if/else, loops—into your CSS preprocessor. Use them to generate component variations or utility classes without repetitive code.
WHY IT EXISTS CSS is declarative, not procedural. This makes writing repetitive styles, like twelve grid columns or five button color variations, tedious and error-prone. Sass control directives exist to introduce logic and automation, reducing manual repetition and making stylesheets more maintainable at scale.
THE MENTAL MODEL Treat Sass control directives like the basic control flow from any programming language, but applied to generating CSS rules. Instead of writing out every single class variation by hand, you write a template and tell Sass how to loop or branch to create the final, static CSS output.
HOW IT WORKS Sass provides four main directives that are processed at compile time. First, @if and @else conditionally include a block of styles based on a boolean expression. Second, @for loops a set number of times, perfect for creating numbered utilities like col-1, col-2. Third, @each iterates over items in a list or map, ideal for generating theme variations from a color map. Finally, @while continues to output a block of styles as long as a condition is true, though it's less common than @for or @each.
WHEN TO USE IT Use control directives for tasks with clear, repetitive patterns. Good examples include generating a set of spacing utilities from a list of values, creating multiple color theme classes for a component based on a map of theme names to colors, or building a responsive grid system with @for loops. They are most powerful inside mixins to create configurable, reusable style patterns.
WHEN NOT TO USE IT Avoid using control directives for logic that could be handled better in the browser. For dynamic theming that a user can change, CSS Custom Properties (variables) are a better fit as they don't require recompiling. Also, avoid overly complex, nested loops. If your Sass logic becomes hard to read, it's a sign you are over-engineering a problem that could be solved with simpler, more composable CSS classes.
ONE CANONICAL EXAMPLE A common use case is generating modifier classes for button colors from a map. Imagine a map theme-colors: ("primary": blue, "danger": red). You can use an @each loop like @each name, color in theme-colors { .btn-#{name} { background-color: color; } }. This single block of Sass compiles to .btn-primary { background-color: blue; } and .btn-danger { background-color: red; }, automating the creation of variants.
Read the original → sass-lang.com
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.