cereal_killer
cereal_killer

Reputation: 13

How to nest calc-variables within other calc-variables in Sass?

How can I link a variable with an calc-value in another variable?

What I do:

$height:                25px;
$size:                  calc(#{$height} - 10px);
$margin:                calc(#{$radiosize} /4);
$padding:               calc(#{$radiosize} *2);

What happens:

$height:                25px;
$size:                  15px;
$margin:                /*does not work*/;
$padding:               /*does not work*/;

CodePen Demo

Upvotes: 1

Views: 2555

Answers (3)

Illya Moskvin
Illya Moskvin

Reputation: 352

In your case, given the Codepen you provided in the comments, you don't need to use calc(). As a rule of thumb, use calc() when you want to mix units, e.g. subtracting a px value from a %.

It seems that you are manipulating px values either (1) with other px, or (2) with unitless numbers, so there is no need to use calc():

$height:                25px;
$size:                  $height - 10px;
$margin:                $size / 4;
$padding:               $size * 2;

Here's the Codepen: https://codepen.io/imoskvin/pen/gXdMgR


However, to answer your actual question: you can now nest calc() inside other calc()'s!

It seems this was the original intent, and the spec has been updated accordingly. Browsers are catching up: your original Codepen now works as intended in Chrome and Firefox.

For more details, see this answer from one of the spec editors.

Upvotes: 0

NewOutlaw
NewOutlaw

Reputation: 64

Actually, it is possible to ship a calc() into an other calc(). Unfortunately with a little Hack:

$var1: 3px;
$var2: 5px;

$innerCalc: '(#{$var1} + #{$var2})';
$actualCalc: calc(#{$innerCalc} / 2); //4px

This will do the trick. It simply put all (incl. Brackets) into your calc, but is still able to resolve the variables. Enjoy. :)

P.S. NEVER forget the whitespaces before and after every operator!

Upvotes: 0

m4n0
m4n0

Reputation: 32355

You cannot nest calc() function inside another calc().

Current compiled CSS:

margin: calc(calc(25px - 10px) /4); /* Incorrect syntax */
padding: calc(calc(25px - 10px) *2); /* Incorrect syntax */

Solution:

Calculate the size variable directly.

$size: $height - 10px;

Forked Codepen

Upvotes: 2

Related Questions