Open In App

SASS Booleans and Boolean Operators

Last Updated : 01 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

SASS supports boolean values (true and false) and provides tools for conditional compilation based on these boolean values. This allows you to control which styles are compiled based on certain conditions, making your CSS more dynamic and adaptable.

Additionally, SASS includes boolean operators (and, or, and not) for logical expressions.

Assigning Boolean Values to Variables

In SASS, you can assign a boolean value (true or false) to a variable just like any other value. These boolean values are useful when used in conditions with mixins or functions.

Example of Boolean Assignment:

$variable: true;
$another-variable: false;

Using Boolean Values in Conditional Compilation

You can use boolean values to conditionally compile blocks of CSS code. This is done by using the @if directive inside mixins or functions. The @if block will only compile if the condition evaluates to true.

Example: Conditional Compilation with Mixins

In this example, we define a mixin that accepts a boolean value and a size. If the boolean value is true, the mixin will generate a rounded button by applying a height and a border radius.

SASS file:

@mixin button-format( $round-button, $size ) {
color: white;
background-color: blue;
width: $size;

@if $round-button {
height: $size;
border-radius: $size / 2;
}
}

.mybutton {
@include button-format(true, 100px);
}

Compiled CSS file:

.mybutton {
color: white;
background-color: blue;
width: 100px;
height: 100px;
border-radius: 50px;
}

Boolean Operators in SASS

SASS provides three boolean operators:

  • and: Returns true if both expressions are true.
  • or: Returns true if any expression is true.
  • not: Returns the opposite of the boolean value.

Binary Operators: and, or

The and operator returns true only if both expressions evaluate to true. The or operator returns true if any of the expressions evaluates to true.

Unary Operator: not

The not operator negates the boolean value. If the expression is true, not will return false and vice versa.

Example of Boolean Operators:

In this example, we demonstrate the use of boolean operators in SASS and output the results using @debug.

See the example below:

$var1: true and true;
$var2: true and false;

$var3: true or false;
$var4: false or false;

$var5: not true;

// @debug will print the values of the variable
// at the compilation time in the terminal.
//------------ values

@debug $var1; // true
@debug $var2; // false

@debug $var3; // true
@debug $var4; // false

@debug $var5; // false

Similar Reads