0
0
SASSmarkup~15 mins

@else and @else if branches in SASS - Deep Dive

Choose your learning style9 modes available
Overview - @else and @else if branches
What is it?
@else and @else if branches are parts of conditional statements in Sass, a style sheet language. They let you choose different styles based on conditions, like picking different clothes for different weather. @else runs if the previous condition was false, and @else if checks another condition if the first was false. This helps write cleaner, smarter CSS styles.
Why it matters
Without @else and @else if, you would have to write many separate conditions or duplicate styles, making your code long and hard to manage. These branches let you handle multiple choices in one place, saving time and reducing mistakes. This means your website styles can adapt easily to different situations, improving design and user experience.
Where it fits
Before learning @else and @else if, you should know basic Sass syntax and how to write simple @if conditions. After mastering these branches, you can explore loops, functions, and mixins in Sass to create even more powerful style rules.
Mental Model
Core Idea
@else and @else if let you pick one path among many by checking conditions in order, like choosing what to wear based on the weather forecast.
Think of it like...
Imagine you decide what to wear each day: if it's raining, wear a raincoat; else if it's cold, wear a jacket; else wear a t-shirt. You check conditions one by one and pick the first matching outfit.
┌───────────────┐
│ Start         │
└──────┬────────┘
       │
       ▼
  ┌───────────┐
  │ @if cond1 │──Yes──▶ Do action 1
  └────┬──────┘
       │No
       ▼
  ┌─────────────┐
  │ @else if c2 │──Yes──▶ Do action 2
  └────┬────────┘
       │No
       ▼
  ┌─────────┐
  │ @else   │──▶ Do default action
  └─────────┘
Build-Up - 7 Steps
1
FoundationBasic @if condition in Sass
🤔
Concept: Learn how to write a simple @if statement to apply styles based on one condition.
In Sass, you can use @if to check a condition and apply styles only if it's true. For example: $theme: light; body { @if $theme == light { background: white; color: black; } } This means if $theme is 'light', the body gets white background and black text.
Result
If $theme is 'light', the CSS will have white background and black text for the body. Otherwise, no styles are added.
Understanding @if is the foundation for controlling styles based on conditions, which is essential for dynamic styling.
2
FoundationWhy multiple conditions need branches
🤔
Concept: Recognize that sometimes one condition is not enough and you need to check several possibilities.
Imagine you want different styles for light, dark, and colorful themes. Using only @if means repeating checks or writing separate blocks: $theme: dark; body { @if $theme == light { background: white; } @if $theme == dark { background: black; } @if $theme == colorful { background: yellow; } } This works but is repetitive and inefficient.
Result
All three @if blocks run independently, so if $theme matches one, only that block applies. But the code is longer and harder to read.
Knowing that multiple separate @if statements can be inefficient sets the stage for learning @else and @else if to streamline code.
3
IntermediateUsing @else for default styles
🤔Before reading on: do you think @else runs when the @if condition is true or false? Commit to your answer.
Concept: @else runs only if the previous @if condition was false, letting you set default styles when no conditions match.
You can write: $theme: dark; body { @if $theme == light { background: white; } @else { background: black; } } Here, if $theme is not 'light', the @else block runs and sets background to black.
Result
For $theme 'dark', the background becomes black because the @if condition is false and @else runs.
Understanding @else helps you provide fallback styles without repeating conditions, making code cleaner and easier to maintain.
4
IntermediateChaining conditions with @else if
🤔Before reading on: do you think @else if can check multiple conditions in order or only one? Commit to your answer.
Concept: @else if lets you check another condition only if the previous @if or @else if was false, enabling multiple choices in one block.
Example: $theme: colorful; body { @if $theme == light { background: white; } @else if $theme == dark { background: black; } @else if $theme == colorful { background: yellow; } @else { background: gray; } } This checks each condition in order and applies the first match.
Result
For $theme 'colorful', the background is yellow. If none match, background is gray from @else.
Knowing how to chain conditions with @else if lets you handle many cases clearly and efficiently in one place.
5
IntermediateHow order affects @else if branches
🤔Before reading on: do you think changing the order of @else if branches changes the styles applied? Commit to your answer.
Concept: The order of @else if branches matters because Sass stops checking once a condition is true.
If you write: $number: 10; .test { @if $number > 5 { color: red; } @else if $number > 0 { color: blue; } } Since $number is 10, the first condition is true, so color is red. The second condition is ignored.
Result
The color is red because the first true condition stops further checks.
Understanding that Sass stops at the first true condition helps you order branches correctly to get the desired styles.
6
AdvancedCombining @else if with variables and functions
🤔Before reading on: do you think you can use functions inside @else if conditions? Commit to your answer.
Concept: You can use variables and functions inside @else if conditions to create dynamic and reusable style logic.
Example: $size: 15px; @mixin font-size-check($size) { @if $size < 12px { font-size: 10px; } @else if $size < 18px { font-size: 14px; } @else { font-size: 20px; } } p { @include font-size-check($size); } This mixin adjusts font size based on the $size variable.
Result
For $size 15px, the font-size becomes 14px because the second condition matches.
Knowing you can combine @else if with variables and functions unlocks powerful, flexible styling patterns.
7
ExpertPerformance and readability with complex @else if chains
🤔Before reading on: do you think very long @else if chains affect Sass compilation speed or code clarity? Commit to your answer.
Concept: Long @else if chains can slow down compilation and reduce readability; structuring conditions or using maps can improve this.
When you have many conditions, writing many @else if branches can get messy: @else if $theme == theme1 {} @else if $theme == theme2 {} ... many more ... Instead, you can use maps and functions to look up styles, reducing code length and improving performance. Example: $theme-colors: ( light: white, dark: black, colorful: yellow ); body { background: map-get($theme-colors, $theme, gray); } This replaces long @else if chains with a simple lookup.
Result
The code is shorter, easier to read, and compiles faster, while still applying correct styles.
Understanding the limits of @else if chains helps you write maintainable and efficient Sass by choosing better patterns.
Under the Hood
Sass processes @if, @else if, and @else statements during compilation. It evaluates conditions in order, stopping at the first true condition and applying its styles. This is done by the Sass compiler parsing the stylesheet, evaluating variables and expressions, and generating CSS accordingly. The branching logic is similar to programming languages but happens before the browser sees the CSS.
Why designed this way?
The design mimics common programming conditional logic to make it intuitive for developers. It allows clear, readable style decisions without duplicating code. Alternatives like separate @if statements exist but can cause redundancy. The ordered evaluation ensures predictable, efficient style generation.
┌───────────────┐
│ Sass Compiler │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Parse Styles  │
└──────┬────────┘
       │
       ▼
┌─────────────────────────────┐
│ Evaluate @if condition       │
│   ├─True─▶ Apply styles      │
│   └─False─▶ Check @else if   │
│           ├─True─▶ Apply     │
│           └─False─▶ Check @else│
│                     └─Apply default styles│
└─────────────────────────────┘
       │
       ▼
┌───────────────┐
│ Generate CSS  │
└───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does @else run if the @if condition is true? Commit to yes or no.
Common Belief:Some think @else always runs after @if, regardless of the condition.
Tap to reveal reality
Reality:@else runs only if the previous @if or @else if condition was false.
Why it matters:If you expect @else to always run, you might overwrite styles unintentionally, causing bugs in your design.
Quick: Can you use multiple @else blocks after one @if? Commit to yes or no.
Common Belief:Some believe you can have many @else blocks after one @if to handle multiple defaults.
Tap to reveal reality
Reality:You can have only one @else block after an @if or @else if chain.
Why it matters:Trying to use multiple @else blocks causes syntax errors and breaks your Sass compilation.
Quick: Does the order of @else if branches affect which styles apply? Commit to yes or no.
Common Belief:Some think the order of @else if branches does not matter because all conditions are checked.
Tap to reveal reality
Reality:Sass stops checking after the first true condition, so order changes which styles apply.
Why it matters:Ignoring order can lead to unexpected styles and bugs that are hard to track.
Quick: Can @else if conditions use complex expressions and functions? Commit to yes or no.
Common Belief:Some think @else if conditions must be simple and cannot use functions or variables.
Tap to reveal reality
Reality:@else if conditions can use any valid Sass expressions, including functions and variables.
Why it matters:Underestimating this limits your ability to write flexible and powerful style logic.
Expert Zone
1
Sass evaluates conditions lazily, so expensive computations inside @else if conditions only run if needed, improving performance.
2
Using maps and functions to replace long @else if chains can make stylesheets more maintainable and scalable in large projects.
3
Nested @if/@else if/@else blocks can create complex logic but should be used sparingly to keep styles readable and debuggable.
When NOT to use
Avoid very long @else if chains for many conditions; instead, use Sass maps with map-get or switch to mixins/functions for better performance and clarity.
Production Patterns
In real projects, developers often use @else if for theme or breakpoint-based styles but replace complex chains with maps or configuration objects to keep code clean and fast.
Connections
Programming if-else statements
Same pattern of conditional branching used in programming languages like JavaScript or Python.
Knowing how if-else works in programming helps understand Sass conditionals because they follow the same logic flow.
Decision trees in data science
Both use ordered condition checks to decide outcomes based on input values.
Understanding decision trees clarifies how Sass picks the first matching condition and stops checking further.
Traffic light control systems
Both systems evaluate conditions in sequence to decide which action to take next.
Seeing Sass conditionals like traffic lights helps grasp the importance of order and exclusive choices.
Common Pitfalls
#1Writing multiple separate @if statements instead of using @else if chains.
Wrong approach:body { @if $theme == light { background: white; } @if $theme == dark { background: black; } @if $theme == colorful { background: yellow; } }
Correct approach:body { @if $theme == light { background: white; } @else if $theme == dark { background: black; } @else if $theme == colorful { background: yellow; } }
Root cause:Misunderstanding that separate @if statements all run independently, causing redundant checks and possible conflicting styles.
#2Placing @else before @else if in a chain.
Wrong approach:body { @if $theme == light { background: white; } @else { background: black; } @else if $theme == colorful { background: yellow; } }
Correct approach:body { @if $theme == light { background: white; } @else if $theme == colorful { background: yellow; } @else { background: black; } }
Root cause:Not knowing that @else must come last and cannot be followed by @else if.
#3Expecting @else to run even if @if condition is true.
Wrong approach:body { @if $theme == light { background: white; } @else { background: black; } // expecting both blocks to apply }
Correct approach:body { @if $theme == light { background: white; } @else { background: black; } }
Root cause:Misunderstanding that @else only runs if the previous condition is false.
Key Takeaways
@else and @else if let you write clear, ordered choices in Sass to apply styles based on conditions.
Only one branch runs in a chain: the first true condition stops further checks, so order matters.
Using @else provides a default style when no conditions match, avoiding missing styles.
Long chains of @else if can be replaced with maps and functions for better performance and readability.
Understanding these branches helps you write smarter, cleaner, and more maintainable stylesheets.