Sass Basics: Operators

Share this article

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.

Key Takeaways

  • Sass operators are essential tools for front-end developers, including assignment, arithmetic, equality, comparison, logical, string and color operators.
  • Arithmetic operators in Sass work only for numbers with compatible units and follow the order of operations, with expressions in parentheses evaluated first and multiplication and division having higher priority than addition and subtraction.
  • Sass supports several types of equality and comparison operators, used in conditional statements to test whether two values are the same or not, or to compare numbers respectively, returning a Boolean value based on their evaluation.
  • Logical operators in Sass allow the testing of multiple conditions within a conditional expression, while string operations allow for concatenation of strings and color operations produce color values through arithmetic operations.

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) < 5) 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.

Frequently Asked Questions about Sass Operators

What are the different types of operators in Sass?

Sass supports several types of operators, including arithmetic, comparison, and logical operators. Arithmetic operators include addition (+), subtraction (-), multiplication (*), and division (/). Comparison operators include equal to (==), not equal to (!=), greater than (>), less than (<), greater than or equal to (>=), and less than or equal to (<=). Logical operators include and, or, and not. These operators allow you to perform various operations on Sass variables and values, making your stylesheets more dynamic and flexible.

How does division work in Sass?

Division in Sass can be a bit tricky because the slash (/) character is also used for other purposes, such as specifying font sizes and color values. To ensure that Sass interprets a slash as a division operator, you must either use parentheses around the operation or use a variable or function for at least one of the operands. For example, both (10px / 2px) and $width / 2 will be interpreted as division operations.

Can I use Sass operators with different data types?

Yes, Sass operators can be used with different data types, but the results may vary depending on the types of values you’re working with. For example, you can add a number and a string in Sass, but the result will be a string. If you try to perform an operation that doesn’t make sense, such as multiplying a string by a color, Sass will throw an error.

How do comparison operators work in Sass?

Comparison operators in Sass work similarly to those in other programming languages. They compare two values and return a boolean result: true if the comparison is true, and false if it’s not. For example, 1 < 2 will return true, while 2 == 3 will return false. You can use comparison operators in conditions to control the flow of your stylesheets.

What are logical operators in Sass and how do they work?

Logical operators in Sass include and, or, and not. They are used to combine or invert boolean values. The and operator returns true if both operands are true, the or operator returns true if at least one operand is true, and the not operator returns the opposite of the operand. For example, true and false will return false, true or false will return true, and not true will return false.

Can I use operators in Sass functions?

Yes, you can use operators in Sass functions. This allows you to create more complex calculations and operations. For example, you could create a function to calculate the average of two numbers like this: @function average($a, $b) { @return ($a + $b) / 2; }.

How does operator precedence work in Sass?

Operator precedence in Sass works similarly to other programming languages. Multiplication and division have higher precedence than addition and subtraction. This means that in an expression like 1 + 2 * 3, the multiplication will be performed first, resulting in 1 + 6, which equals 7. You can use parentheses to change the order of operations.

Can I use Sass operators with colors?

Yes, you can use some Sass operators with colors. For example, you can add and subtract colors, which will add or subtract the RGB values of the colors. You can also multiply a color by a number, which will multiply the RGB values of the color by the number.

How can I use Sass operators to create responsive designs?

Sass operators can be very useful for creating responsive designs. For example, you can use arithmetic operators to calculate widths, heights, and other dimensions based on variables. This allows you to create flexible layouts that adapt to different screen sizes and resolutions.

Can I use Sass operators in control directives?

Yes, you can use Sass operators in control directives such as @if, @for, @each, and @while. This allows you to create complex conditions and loops, making your stylesheets more dynamic and powerful. For example, you could use a @for loop with a multiplication operator to generate a series of classes with increasing font sizes.

George MartsoukosGeorge Martsoukos
View Author

George is a freelance web developer and an enthusiast writer for some of the largest web development magazines in the world (SitePoint, Tuts+). He loves anything related to the Web and he is addicted to learning new technologies every day.

Sass Basicssass functionssass mixinssassbasicsStuR
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week