0
0
SASSmarkup~3 mins

Why @if conditional logic in SASS? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

Discover how a simple condition can save you hours of tedious CSS rewriting!

The Scenario

Imagine you want to style a button differently depending on whether it is primary or secondary. You write separate CSS rules for each case manually.

The Problem

If you want to change the style for many buttons or add new conditions, you must copy and edit many CSS blocks. This is slow, repetitive, and easy to make mistakes.

The Solution

The @if conditional logic in Sass lets you write one style block that changes automatically based on conditions. This keeps your code clean and easy to update.

Before vs After
Before
button-primary { background: blue; color: white; }
button-secondary { background: gray; color: black; }
After
@if $type == 'primary' {
  background: blue;
  color: white;
} @else {
  background: gray;
  color: black;
}
What It Enables

You can create flexible styles that adapt automatically, saving time and reducing errors.

Real Life Example

Styling a website's theme where buttons, alerts, or cards change colors based on user preferences or states.

Key Takeaways

Manual CSS for different cases is repetitive and error-prone.

@if lets you write conditional styles in one place.

This makes your styles easier to maintain and update.