SASS | negative variable value
SASS variables are quite useful in writing maintainable styling code for web pages. Often, we require different components of a page to have the same value for a stylistic property. In such a scenario, assigning the value to a variable and using it wherever required reduces the amount of effort needed to make changes to the styling in the future. We might also require the negation of a variable’s value for a property sometimes. For instance, consider the SASS code given below:
$marg: 20px ; #div 1 { margin : 0 20px 0 -20px ; } |
The property values 20px
and -20px
can be substituted with the $marg variable. The obvious way to go about this would be:
$marg: 20px ; #div 1 { margin : 0 $marg 0 -$marg; } |
However, on compilation, this generates the following css:
$marg: 20px ; #div 1 { margin : 0 20px -20px ; } |
This is because the SASS compiler treats 0 -$marg
as a subtraction operation and outputs -20px. Hence, whenever we wish to use the negation of a variable, it might lead to undesirable output CSS, since the SASS compiler might mistake the intent to be binary subtraction.
Now there are multiple ways in which this problem can be solved.
-
Using parenthesis: Enclosing the variable with a parenthesis will prevent the compiler from performing subtraction.
$marg: 20px;
#div1 {
margin: 0 $marg 0 (-$marg);
}
-
Performing multiplication with a negative number: Simply multiplying the variable with -1 will generate its negation, while retaining its original units.
$marg:
20px
;
#div
1
{
margin
:
0
$marg
0
-1
*$marg;
}
-
Using interpolation: Interpolating a value converts it into an unquoted string. It can be used to obtain the negation of a variable’s value. However, this is not recommended since the unquoted string in the output CSS will look like a number, but not work with numerical operators and functions, which can lead to misleading code.
$marg: 20px;
#div1 {
margin: 0 $marg 0 -#{$marg};
}
In all the above approaches, the following CSS is obtained on compilation:
#div1 { margin: 0 20px 0 -20px; }
In this way, we can utilize a SASS variable for both positive and negative use cases, hence promoting variable reuse and more maintainable code.