Sass Control Directives

Sass Tutorial

Sass Control Directives – Complete Practical Guide

Sass control directives allow you to add logic and flow control to your stylesheets—similar to programming languages.

Think of control directives as decision-making and looping tools for Sass.

They help you:

  • Generate CSS dynamically

  • Avoid repetition

  • Build scalable design systems


1. What Are Sass Control Directives?

It let Sass:

  • Make decisions (@if)

  • Loop over values (@for, @each, @while)

  • Generate multiple selectors or rules automatically

They work at compile time, not in the browser.


2. @if, @else if, @else

Used for conditional logic.

Syntax

Example


 


3. Using @if with Mixins (Very Common)


 


4. Comparison & Logical Operators

Comparison

== != > < >= <=

Logical

and or not

Example


5. @for Loop

Used when you know how many times to loop.

Syntax

  • through → includes end

  • to → excludes end

Example

Output

.col-1 { width: 25%; }
.col-2 { width: 50%; }
.col-3 { width: 75%; }
.col-4 { width: 100%; }

6. @each Loop (Most Useful)

Used to loop over lists or maps.

6.1 Looping a List


 


6.2 Looping a Map (Very Common)


 

Perfect for design systems


7. @while Loop

Used when looping depends on a condition.

Use carefully—can cause infinite loops.

Example


 


8. String Interpolation (#{})

Used heavily with control directives.


 

Essential for dynamic selectors.


9. Real-World Use Cases

9.1 Grid Systems


9.2 Utility Classes


 


9.3 Theme Variations


10. Common Mistakes

  •  Expecting runtime behavior
  •  Overusing @while 
  • Writing complex logic in CSS
  •  Forgetting to update loop counters
  •  Using control directives for layout instead of structure

11. Performance Considerations

  • Runs at compile time

  • No impact on browser performance

  • Can generate large CSS if misused

  • Keep loops controlled and intentional


12. Interview-Level Questions

Q: What are Sass control directives?
They add logic like conditions and loops to Sass.

Q: Difference between @for and @each?
@for loops numbers, @each loops lists/maps.

Q: When should you avoid @while?
When loop count is predictable.

Q: Do control directives run in the browser?
No, only during compilation.


Best Practices Summary

  • Use @each for design systems

  • Prefer @for for grids and sequences

  • Keep logic simple

  • Avoid deep or complex conditions

  • Use mixins + directives together


Final Summary

  • It add logic to CSS

  • Include @if, @for, @each, @while

  • Powerful for utilities, grids, and themes

  • Compile-time only (safe & fast)

  • Essential for scalable Sass architecture

You may also like...