Adding Conditional Logic with @if and @else

Tutorial 2 of 5

Adding Conditional Logic with @if and @else in SASS

1. Introduction

The goal of this tutorial is to introduce you to the use of @if and @else directives in SASS/SCSS to add conditional logic to your stylesheets. You will learn how to create dynamic stylesheets that can adapt to different conditions.

Prerequisites: You should have a basic understanding of CSS and a general knowledge of SASS/SCSS.

2. Step-by-Step Guide

In SASS, the @if and @else directives allow you to apply styles conditionally based on the evaluation of certain conditions. This can make your stylesheets more dynamic and adaptable.

The syntax for the @if directive is as follows:

@if condition {
  // styles to apply if condition is true
} @else {
  // styles to apply if condition is false
}

The condition can be any SASS expression that returns a boolean value (true or false).

3. Code Examples

Example 1:

$bg-color: blue;

body {
  @if $bg-color == blue {
    background-color: blue;
  } @else {
    background-color: white;
  }
}

In the above example, the background color of the body will be blue if the $bg-color variable is 'blue'. Otherwise, the background color will be white.

Example 2:

$width: 800px;

.container {
  @if $width > 768px {
    width: 80%;
  } @else if $width > 480px {
    width: 90%;
  } @else {
    width: 100%;
  }
}

Here, if the $width variable is greater than 768px, the width of the .container will be 80%. If the $width is greater than 480px but less than or equal to 768px, the width will be 90%. For all other cases, the width will be 100%.

4. Summary

In this tutorial, we covered how to use the @if and @else directives in SASS/SCSS to add conditional logic to your stylesheets. You should now be able to write more dynamic and adaptable styles.

Next, you can explore other SASS features like mixins, functions, and loops. You can also learn more about CSS preprocessors in general.

5. Practice Exercises

Exercise 1: Write a SASS script to set the font size of a paragraph to 16px if the screen width is less than 768px. If the screen width is greater than or equal to 768px, set the font size to 20px.

Solution:

$screen-width: 800px;

p {
  @if $screen-width < 768px {
    font-size: 16px;
  } @else {
    font-size: 20px;
  }
}

Exercise 2: Define a SASS variable $theme with a value of 'dark'. If the $theme is 'dark', set the background color of the body to black and the color to white. If the $theme is 'light', set the background color to white and the color to black.

Solution:

$theme: dark;

body {
  @if $theme == dark {
    background-color: black;
    color: white;
  } @else if $theme == light {
    background-color: white;
    color: black;
  }
}

Keep practicing with different conditions and styles to get a good grasp of using @if and @else in SASS/SCSS.