Sass Basics: Operators

George Martsoukos
Share

Sass is quite popular and tends to be an essential tool for every front-end developer. Sitepoint has already published some introductory articles about this CSS preprocessor language.

In this article, we’ll continue exploring Sass by diving into its operations.

Note: The examples will be based on Ruby Sass. I also suggest you to have a look at Hugo’s article, which discusses Sass-Compatibility.

Assignment Operator

Sass uses the colon (:) operator to define a variable. For instance:

$main-color: lightgray;

Arithmetic Operators

Arithmetic operators are used to perform the standard arithmetic operations.

Here are the arithmetic operators that Sass supports:

Operator Description
+ Addition
Subtraction
* Multiplication
/ Division
% Remainder

As we’ll see in an upcoming section, the addition operator (+) can also be used to concatenate strings.

Note that the operators above work only for numbers with compatible units:

h2 {
    font-size: 5px + 2em; // error incompatible units

    font-size: 5px + 2; // 7px
}

Moreover, multiplying two numbers of the same unit together will produce invalid CSS:

h2 {
    font-size: 5px * 2px; // invalid CSS
}

As you might know, the / symbol is part of CSS shorthand properties. For example:

font: 16px / 24px Arial sans-serif;

background: url("http://example.com") no-repeat fixed center / cover;

But, as already mentioned Sass can take advantage of the forward slash (/) to perform the division operation.

So, let’s see how Sass understands this symbol:

h2 {
    font-size: 16px / 24px // Outputs as CSS

    font-size: (16px / 24px) // Uses parentheses, does division

    font-size: #{$base-size} / #{$line-height}; // Uses interpolation, outputs as CSS

    font-size: $base-size / $line-height // Uses variables, does division

    opacity: random(4) / 5; // Uses a function, does division

    padding-right: 2px / 4px + 3px // Uses an arithmetic expression, does division
}

Sass takes care of the order of operations (operator precedence). For instance, here are some general rules:

  • Expressions in parentheses are evaluated first.
  • The multiplication (*) and division (/) operators have a higher priority compared to the addition (+) and subtraction operators (-).

An example of them is shown below:

h2 {
     width: 3px * 5 + 5px; // 20px

     width: 3 * (5px + 5px); // 30px

     width: 3px + (6px / 2) * 3; // 12px
 }

Equality Operators

Equality operators are used in conditional statements to test whether two values are the same or not. Based on their evaluation, they return a Boolean value.

Sass supports the following equality operators:

Operator Description
== Equal to
!= Not equal to

These are supported for all the types.

Let’s take a look at two examples.

In our first example, we use the equality operator (==) to test the type of the $font argument and print the appropriate message. Here’s the code:

@mixin font-fl($font){
    &:after {
        @if(type-of($font) == string) {
            content: 'My font is: #{$font}.';
        } @else {
            content: 'Sorry, the argument #{$font} is a #{type-of($font)}.';
        }
    }
}

h2{
    @include font-fl(sans-serif);
}

This compiles to:

h2:after {
    content: 'My font is: sans-serif.';
}

In our second example, we define a list and check the length of its items. Using the modulus (remainder) operator (%), we evaluate their length and finally set the color property of the h2 element. Below is the corresponding code:

$list: "tomato", "lime", "lightblue";

@mixin fg-color($property) {
    @each $item in $list {
        $color-length: str-length($item);
        @if( $color-length % 2 != 0 ) {
            #{$property}: unquote($item);
        }
    }
}

h2 {
    @include fg-color(color);
}

And the generated CSS:

h2 {
    color: lightblue;
}

It’s worth mentioning that Sass doesn’t support the strict equality operator (===) which you will find in other computer languages. However, as you’ll notice in the next example, Sass handles the equality operator in the same way as other languages handle the strict equality operator.

// comparison in Javascript
("5" == 5) // returns true

("5" === 5) // returns false

// comparison in Sass
("5" == 5) // returns false

(20px == 20) // returns true (this does not work in LibSass)

Comparison Operators

Similar to equality operators, comparison operators are used to compare numbers.

Sass supports the following comparison operators:

Operator Description
> Greater than
>= Greater than or equal to
Less than
Less than or equal to

Here’s a simple example:

$padding: 50px;

h2 {
    @if($padding <= 20px) {
        padding: $padding;
    } @else {
        padding: $padding / 2;
    }
}

And the compiled CSS:

h2 {
    padding: 25px;
}

Logical Operators

Logical operators allow us to test multiple conditions within a conditional expression.

Sass supports the following logical operators:

Operator Conditions Description
and x and y true if both x and y are true
or x or y true if either x or y is true
not x true if x is not true

Let’s explain them through an example.

We define a list map, which contains button states as keys and the corresponding colors as values. Then, we create a condition to evaluate its length. If the entire condition evaluates to true, we apply a background-color to the h2 element. Below is our initial Sass code:

$list-map: (success: lightgreen, alert: tomato, info: lightblue);

@mixin button-state($btn-state) {
    @if (length($list-map) > 2 or length($list-map) < 5) {
        background-color: map-get($list-map, $btn-state);
    }
}

.btn {
    @include button-state(success);
}

And the generated CSS:

.btn {
    background-color: lightgreen;
}

As we can see, our condition returns true. That happens because the map’s length is 3 and thus, the nested conditions (length($list-map) > 2length($list-map) ) return true.

Notice although the differences if we modify the expression:

@if (length($list-map) > 2 or not (length($list-map) == 3)) {...} // returns true, applies background-color

@if (length($list-map) > 2 and not (length($list-map) == 3)) {...} // returns false, doesn't apply background-color

String Operations

As we have already discussed, the addition operator (+) provides us with a way to concatenate strings.

Here are the basic rules:

  • If we add a quoted string (that’s said before the + operator) to an unquoted string, the result is a quoted string.
  • If we add an unquoted string (that’s said before the + operator) to a quoted string, the result is an unquoted string.

To demonstrate this, we’ll take a look at the following example. Our Sass code is shown below:

@mixin string-concat {
    &:after {
        content: "My favorite language is " + Sass;
        font: Arial + " sans-serif";
    }
}

h2 {
    @include string-concat;
}

The corresponding CSS:

h2:after {
    content: "My favorite language is Sass";
    font: Arial sans-serif;
}

Moreover, we can place dynamic values within our strings by taking advantage of interpolation (we have already used it!). Note also that null values are not printed. Here’s an example similar to last one:

@mixin string-concat ($language) {
    &:after {
        content: "My favorite language is #{$language}";

        // second way without using interpolation
        //content: "My favorite language is " + $language;
    }
}

h2 {
    @include string-concat(Sass);
}

The resulting CSS:

h2:after {
    content: "My favorite language is Sass";
}

Color Operations

In the second section, we analyzed the arithmetic operators. One interesting thing is that we can also use them to produce color values.

Let’s have a look.

Here’s our Sass code:

h2 {
    color: #468499 + #204479;
}

And the generated CSS:

h2 {
    color: #66c8ff;
}

So, how do these color operations work? Sass performs the corresponding calculation on pairs. That means:

46+20=66 (red color), 84+44=c8 (green color), and 99+79=ff (blue color).

Keep in mind that hex values are a combination of red, green, and blue color values. Moreover, for their representation the numbers 0-9 and the letters A-F are used.

Below is our last example. The only difference with the previous one is that we now use the rgba function to represent the colors.

Our Sass:

h2 {
    color: rgba(70, 132, 153, 1) + rgba(32, 68, 121, 1);

    // error alpha channels must be equal
    color: rgba(70, 132, 153, .9) + rgba(32, 68, 121, .7);
}

Note that when you use the rgba or hsla color functions, the colors should have the same alpha value. Otherwise, Sass will throw an error.

Conclusion

In this article, I explained the Sass operators. As you have seen, some are similar to the operators that other programming languages support. Hopefully, this article helped you enhance your skills about this awesome language. Last but not least, you can find all the article’s examples on this Sassmeister page.