0
0
SASSmarkup~5 mins

@else and @else if branches in SASS

Choose your learning style9 modes available
Introduction

Use @else and @else if to make decisions in your styles. They help you choose different styles based on conditions.

When you want to apply different colors based on a theme variable.
When you need to change layout styles depending on screen size or device type.
When you want to style buttons differently based on their state (like primary, secondary).
When you want to avoid repeating code by grouping related style choices.
When you want to make your styles easier to read and maintain by handling multiple conditions.
Syntax
SASS
@if condition {
  // styles here
} @else if another-condition {
  // other styles here
} @else {
  // fallback styles here
}

The @if block checks the first condition.

The @else if block checks another condition if the first is false.

The @else block runs if all previous conditions are false.

Examples
Sets background white if theme is light, otherwise black.
SASS
@if $theme == light {
  background: white;
} @else {
  background: black;
}
Chooses font size based on size variable with a fallback.
SASS
@if $size == small {
  font-size: 1rem;
} @else if $size == medium {
  font-size: 1.5rem;
} @else {
  font-size: 2rem;
}
Sample Program

This code styles a button differently based on the $theme variable. It uses @if, @else if, and @else to pick the right colors.

SASS
@use 'sass:color';

$theme: dark;

.button {
  @if $theme == light {
    background-color: white;
    color: black;
  } @else if $theme == dark {
    background-color: black;
    color: white;
  } @else {
    background-color: gray;
    color: black;
  }
  padding: 1rem 2rem;
  border-radius: 0.5rem;
  font-weight: bold;
}
OutputSuccess
Important Notes

Only one block runs: the first true condition's block.

You can have many @else if branches to check multiple conditions.

Always include an @else for a safe fallback style.

Summary

@else if lets you check more conditions after the first @if.

@else runs if no other conditions are true.

Use these to write clear, organized style rules that change based on variables.