SASS Variable in CSS calc() function

CSS is itself a good language for web designing but stylesheets are becoming more complex, larger, and even harder to maintain. That’s where a preprocessor like Sass comes in action and helps us to use features which don’t even exist in CSS.

The calc() function is a function that takes a single expression as its parameter and taking the expression’s value as the result. The expression can be any simple expression including the basic arithmetic operators like addition, subtraction, multiplication and division.

The only place we can use calc() function is in values and also for a part of some property.
The calc() CSS function allows us to perform calculations while specifying the CSS property values like <length>, <frequency>, <angle>, <time>, <percentage>, <number>, or <integer>.

The calc() function is defined in the CSS spec since the mathematical expression of calc() conflicts with the Sass’s arithmetic.

Approach:



Using a Sass variable inside calc() function: Variables in CSS have the ability to have different values for different elements but Sass variables can have only one value at a time.
The variables in Sass are imperative which means if we use a variable and then change its value then the earlier use will stay the same.
In Sass, the most common use for variables is to drop variables directly into Sass stylesheets but at times doing that is not the only thing required. There are certain situation where interpolation syntax inside of CSS functions is necessary.
Calc() is not compiled by Sass but by the browser itself so it needs to have all values properly written in the function.
Interpolation means just the replacement of a placeholder with its literal value so in case of processing Sass to CSS all the references to variables are probably setting up an interpolation.

There are times where the Sass processors will not perform the substitution unless there’s a explicitly specified interpolation using the #{} syntax.  
The Sass variable in CSS calc() function is defined by using a Reserved symbol ($)
There’s a simple implementation of using a Sass variable in CSS calc() function given below :

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

$a: 40%; 
$b: 10px; 
    
.class { 
  height: calc(#{$a} - #{$b}); 
}

chevron_right


Compiled File :

.class {
 height: calc(40% - 10px);
}
My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

6


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.