Home » SASS if Directive

SASS if Directive

by Online Tutorials Library

Sass @if Directive

The @if directive specifies the execution of code statements according to the result of the expression. A @if statement can be used with several @if else statements and one @else statement.

There are two types of @if directive:

  • @if directive
  • @else if directive

@if Directive

The Sass @if directive accepts SassScript expressions and uses the nested styles if the expression returns anything other than false or null.

For example: If you use the following SCSS file.

SCSS Syntax:

After compilation, it will create a CSS file having following code:

CSS Syntax:

Sass @if Directive Example

Let’s take an example to demonstrate the usage of Sass @if directive. We have an HTML file named “simple.html”, having the following data.

HTML file: simple.html

Create a SCSS file named “simple.scss”, having the following data.

SCSS file: simple.scss

Put the both file inside the root folder.

Now, open command prompt and run the watch command to tell SASS to watch the file and update the CSS whenever SASS file is changed.

Execute the following code: sass –watch simple.scss:simple.css

It will create a normal CSS file named “simple.css” in the same directory automatically.

For example:

Sass If directive1

The created CSS file “simple.css” contains the following code:

Now, execute the above html file, it will read the CSS value.

Output: Sass If directive2

You may also like