0
0
SASSmarkup~15 mins

@if conditional logic in SASS - Deep Dive

Choose your learning style9 modes available
Overview - @if conditional logic
What is it?
The @if conditional logic in Sass lets you make decisions in your stylesheets. It works like a simple question: if something is true, do one thing; if not, do something else. This helps you write styles that change depending on conditions, making your CSS smarter and more flexible. It is similar to how you decide what to wear based on the weather.
Why it matters
Without @if, you would have to write many separate styles for every situation, making your CSS long and hard to manage. @if lets you keep your styles organized and adaptable, saving time and reducing mistakes. It makes your design system easier to maintain and update, especially when you want to change colors, sizes, or layouts based on different rules.
Where it fits
Before learning @if, you should understand basic Sass syntax like variables and nesting. After mastering @if, you can learn about @else and @else if for more complex decisions, and then explore mixins and functions to reuse conditional logic efficiently.
Mental Model
Core Idea
@if in Sass is a way to ask a question in your styles and choose what CSS to write based on the answer.
Think of it like...
It's like choosing what to wear: if it's cold, wear a jacket; if not, wear a t-shirt. The @if checks the condition and picks the right style.
┌───────────────┐
│ Condition?    │
├───────────────┤
│ true  │ false │
│       │       │
▼       ▼       ▼
Apply   Skip    
styles  styles  
Build-Up - 7 Steps
1
FoundationUnderstanding basic @if syntax
🤔
Concept: Learn how to write a simple @if statement in Sass to check a condition.
In Sass, you write @if followed by a condition in parentheses. If the condition is true, the code inside the block runs. For example: $color: blue; @if ($color == blue) { body { background-color: blue; } } This means: if $color is blue, set the background color to blue.
Result
If $color is blue, the body background becomes blue in the CSS output.
Understanding the basic syntax is the first step to making your styles respond to different values.
2
FoundationUsing variables in conditions
🤔
Concept: Use Sass variables inside @if to compare values and control styles.
Variables hold values like colors or numbers. You can compare them in @if to decide styles. $size: 10px; @if ($size > 5px) { p { font-size: $size; } } This means: if $size is bigger than 5px, set paragraph font size to $size.
Result
Paragraphs get font size 10px because 10px is greater than 5px.
Using variables in conditions lets you write flexible styles that change with your design settings.
3
IntermediateAdding @else for alternative styles
🤔Before reading on: do you think @else runs when the @if condition is true or false? Commit to your answer.
Concept: Learn how to use @else to provide styles when the @if condition is false.
Sometimes you want to do one thing if true, and another if false. Use @else after @if: $theme: dark; @if ($theme == light) { body { background: white; } } @else { body { background: black; } } If $theme is not light, the @else block runs.
Result
Since $theme is dark, the body background becomes black.
Knowing @else lets you handle both sides of a decision, making your styles cover all cases.
4
IntermediateUsing @else if for multiple choices
🤔Before reading on: do you think you can check more than two conditions with @if alone? Commit to your answer.
Concept: Use @else if to check several conditions in order, like a chain of questions.
When you have many options, use @else if: $device: tablet; @if ($device == phone) { font-size: 12px; } @else if ($device == tablet) { font-size: 16px; } @else { font-size: 20px; } This picks font size based on device type.
Result
Since $device is tablet, font size is 16px.
Using @else if lets you write clear, readable styles for many conditions without repeating code.
5
IntermediateCombining conditions with logical operators
🤔Before reading on: do you think you can check two conditions at once in @if? Commit to your answer.
Concept: Use logical operators like and, or to combine multiple conditions in @if.
You can check more than one thing: $width: 800px; $height: 600px; @if ($width > 500px and $height > 500px) { .box { display: block; } } This means: if width and height are both bigger than 500px, show the box.
Result
Since both width and height are over 500px, .box is displayed.
Combining conditions lets you create precise rules that depend on multiple factors.
6
AdvancedUsing @if inside mixins for reusable logic
🤔Before reading on: do you think @if can be used inside mixins to change styles dynamically? Commit to your answer.
Concept: Put @if inside mixins to create reusable style blocks that adapt based on input values.
@mixin button-style($type) { @if ($type == primary) { background: blue; color: white; } @else if ($type == secondary) { background: gray; color: black; } @else { background: white; color: black; } } .button { @include button-style(primary); } This mixin changes button colors based on $type.
Result
The .button gets blue background and white text for primary type.
Using @if in mixins makes your styles modular and easy to update across your project.
7
ExpertPerformance and pitfalls of complex @if logic
🤔Before reading on: do you think complex nested @if statements slow down Sass compilation significantly? Commit to your answer.
Concept: Understand how too many or deeply nested @if statements can affect Sass performance and maintainability.
Sass compiles styles by running all @if checks. Complex or nested conditions increase compile time and make code harder to read. For example: @if ($a) { @if ($b) { // styles } } This can be rewritten for clarity or replaced with maps or functions for better performance.
Result
Overusing @if can slow down compilation and confuse developers.
Knowing the limits of @if helps you write efficient, maintainable Sass that scales well.
Under the Hood
When Sass compiles, it reads your @if statements and evaluates the conditions using the current variable values. If the condition is true, it includes the styles inside the block in the final CSS. If false, it skips them. This happens before the CSS is sent to the browser, so the output CSS only contains the styles that passed the conditions.
Why designed this way?
Sass was designed to extend CSS with programming features like variables and logic to reduce repetition and manual changes. The @if statement mimics programming conditionals to let developers write smarter stylesheets. Alternatives like writing separate CSS files for each condition were less efficient and harder to maintain.
Sass source code
     │
     ▼
  Evaluate @if condition
     │
 ┌───┴────┐
 │ True   │ False
 │        │
Include   Skip
styles    styles
     │
     ▼
Generate CSS output
Myth Busters - 4 Common Misconceptions
Quick: Does @if in Sass run in the browser or during compilation? Commit to your answer.
Common Belief:Many think @if runs in the browser like JavaScript conditionals.
Tap to reveal reality
Reality:@if runs only during Sass compilation, before CSS reaches the browser.
Why it matters:Thinking @if runs in the browser leads to expecting dynamic style changes that won't happen, causing confusion and bugs.
Quick: Can you use @if to check CSS property values directly? Commit to your answer.
Common Belief:Some believe @if can check actual CSS property values after rendering.
Tap to reveal reality
Reality:@if can only check Sass variables or expressions during compilation, not live CSS values.
Why it matters:Misunderstanding this causes attempts to write dynamic CSS that Sass cannot handle, leading to broken styles.
Quick: Does @if support complex JavaScript-like expressions? Commit to your answer.
Common Belief:People often think @if supports all JavaScript operators and functions.
Tap to reveal reality
Reality:@if supports a limited set of operators and Sass-specific functions, not full JavaScript syntax.
Why it matters:Expecting full JS features causes syntax errors and frustration when writing Sass.
Quick: Can @if be used to conditionally include CSS selectors? Commit to your answer.
Common Belief:Some believe @if can conditionally add or remove selectors dynamically at runtime.
Tap to reveal reality
Reality:@if only controls what CSS is generated during compilation, selectors are fixed in output.
Why it matters:This misconception leads to expecting runtime selector changes, which CSS alone cannot do.
Expert Zone
1
Sass evaluates all @if conditions at compile time, so variables must be set before compilation; runtime changes require other tools.
2
Using maps and functions can often replace complex @if chains for cleaner, more maintainable code.
3
Nested @if statements can be flattened using @else if to improve readability and reduce compile time.
When NOT to use
Avoid using @if for runtime style changes; use JavaScript or CSS custom properties instead. Also, for very complex style variations, consider design tokens or CSS-in-JS solutions that handle dynamic logic better.
Production Patterns
In production, @if is commonly used inside mixins and functions to create themeable components, responsive utilities, and design systems that adapt based on variables like color schemes or device sizes.
Connections
JavaScript if statements
Similar pattern of conditional logic in programming languages
Understanding @if in Sass helps grasp how programming languages use conditions to control behavior, bridging CSS and coding logic.
Feature flags in software development
Both control what features or styles are included based on conditions
Knowing how @if toggles styles based on variables is like how feature flags enable or disable software features, showing a shared approach to conditional control.
Decision trees in management
Both use step-by-step conditions to choose outcomes
Seeing @if as a decision tree clarifies how multiple conditions guide choices, a concept used in business and problem-solving.
Common Pitfalls
#1Writing @if without parentheses around the condition
Wrong approach:@if $color == blue { body { background: blue; } }
Correct approach:@if ($color == blue) { body { background: blue; } }
Root cause:Sass syntax requires parentheses for conditions; missing them causes errors.
#2Using assignment (=) instead of comparison (==) in @if
Wrong approach:@if ($size = 10px) { p { font-size: $size; } }
Correct approach:@if ($size == 10px) { p { font-size: $size; } }
Root cause:Confusing assignment with comparison leads to unexpected behavior or errors.
#3Over-nesting @if blocks making code hard to read
Wrong approach:@if ($a) { @if ($b) { @if ($c) { // styles } } }
Correct approach:@if ($a and $b and $c) { // styles }
Root cause:Not combining conditions leads to complex, unreadable code and slower compilation.
Key Takeaways
@if in Sass lets you write styles that change based on conditions, making CSS smarter and easier to manage.
It runs only during compilation, so it cannot react to changes after the page loads.
Using @else and @else if expands your ability to handle multiple style scenarios clearly.
Combining conditions with logical operators allows precise control over when styles apply.
Overusing or nesting @if can hurt performance and readability; use mixins, functions, or maps for complex logic.