0
0
SASSmarkup~5 mins

@if conditional logic in SASS

Choose your learning style9 modes available
Introduction

The @if directive lets you choose styles based on conditions. It helps you write flexible CSS that changes depending on your rules.

You want to apply different colors based on a variable value.
You need to change layout styles depending on screen size or theme.
You want to avoid repeating code by choosing styles conditionally.
You want to create reusable style blocks that adapt to inputs.
Syntax
SASS
@if <condition> {
  // styles here
} @else if <condition> {
  // other styles
} @else {
  // fallback styles
}
Conditions use simple expressions like $var == value or $var > 10.
You can chain multiple @else if for several choices.
Examples
Sets background white if theme is light, else black.
SASS
$theme: light;

@if $theme == light {
  body {
    background: white;
  }
} @else {
  body {
    background: black;
  }
}
Chooses box width based on size variable.
SASS
$size: 15;

@if $size > 20 {
  .box {
    width: 200px;
  }
} @else if $size > 10 {
  .box {
    width: 150px;
  }
} @else {
  .box {
    width: 100px;
  }
}
Sample Program

This code sets the page background and text color based on the $mode variable. If $mode is dark, background is black and text is white. If light, background is white and text is black. Otherwise, it uses gray background.

SASS
@use 'sass:color';

$mode: dark;

body {
  @if $mode == light {
    background-color: white;
    color: black;
  } @else if $mode == dark {
    background-color: black;
    color: white;
  } @else {
    background-color: gray;
    color: black;
  }
  font-family: Arial, sans-serif;
  padding: 2rem;
}
OutputSuccess
Important Notes

Use @if to keep your styles clean and avoid repeating similar code.

Remember to test your conditions carefully to avoid unexpected styles.

Summary

@if lets you write styles that change based on conditions.

You can use @else if and @else for multiple choices.

This helps make your CSS flexible and easier to maintain.