8

SCSS(Sass) variable vs CSS function

 4 years ago
source link: https://isamrish.medium.com/sass-variable-vs-css-function-56f09cfa2d9b
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

CSS provides some functions such as calc , var etc. If you are using these functions in SCSS and if you are passing the SCSS variable, you will have to be a bit careful because how you use a SCSS variable in the SCSS function is a bit different than how you will use the SCSS variable in the CSS function.

SCSS variable in scss function

In the case of the SCSS variable, in the SCSS function, you can directly use it such as

scss

$base: 25px;@function multiply($x, $multiplier) {
@return $x * $multiplier;
}.box {
width: multiply($base, 10);
}

result (after converting to CSS)

.box {
width: 250px;
}

SCSS variable in CSS function

But in the case of the CSS function, you will have to wrap the variable by #{} . #{} is called interpolation.

scss

$base: 25px;.box {
width: calc(#{$base} * 10);
}

Result:

.box {
width: calc(25px * 10);
}

What if we use the variable without interpolation

Without interpolation, the result would be

.box {
width: calc($base * 10);
}

Here, the width would have an invalid value since the calc function doesn’t know (parse) about the $base.

According to the definition of calc from here

A calc() function contains a single calculation, which is a sequence of values interspersed with operators, and possibly grouped by parentheses (matching the <calc-sum> grammar), which represents the result of evaluating the expression using standard operator precedence rules (* and / bind tighter than + and -, and operators are otherwise evaluated left-to-right).

So $base would not be any valid argument for calc function, we convert it to string using interpolation #{} . Now value would be 25px as a string which is a valid calc argument.

In the same way, other functions will also return invalid values since $base would not be parsable.

I hope that you would be careful while using the SCSS variable in the CSS function.

That’s it!!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK