Sass - if() Function



Description

Based on the condition, this built-in if() function returns only one result from two possible outcomes. The result of the function can be referred to the variable that may not be defined or to have further calculations.

Syntax

if( expression, value1, value2 )

Example

The following example demonstrates the use of if() function in the SCSS file −

if_function.html

<html>
   <head>
      <title>Control Directives & Expressions</title>
      <link rel = "stylesheet" type = "text/css" href = "style.css"/>
   </head>
   
   <body>
      <h2>Welcome to TutorialsPoint</h2>
   </body>
</html>

Next, create file style.scss.

style.scss

h2 {
   color: if( 1 + 1 == 2 , green , red);
}

You can tell SASS to watch the file and update the CSS whenever SASS file changes, by using the following command −

sass --watch C:\ruby\lib\sass\style.scss:style.css

Next, execute the above command; it will create the style.css file automatically with the following code −

style.css

h2 {
   color: green; 
}

Output

Let us carry out the following steps to see how the above given code works −

  • Save the above given html code in if_function.html file.

  • Open this HTML file in a browser, an output is displayed as shown below.

Sass Control Directives & Expressions
sass_control_directives_expressions.htm
Advertisements