11

I want to combine CSS-variables and calc(), but like mentioned in this thread before (that has no precise answer) there seems to be a problem if you do things like the follwing:

--a: 1;
--b: 2; 
--result: calc(var(--a) + var(--b));

The output for this example should be 3 of course, but if you use var(--result) it just has the value var(calc(1 + 2)).

Note: I don't want to use a preprocessor (like sess or lass), just native CSS.

So my question is: Can you somehow force the calc()-function to be executed before its result is used in var(--result)?

Thanks in advance!

0

1 Answer 1

14

CSS is not C++, so these aren't instructions to be exucted sequentially, these are CSS declaration.

--result is equal to calc(var(--a) + var(--b)) and only when you will use the variable the browser will do the final calculation because --a and --b may change depending on the element so saying that --result should be equal to 3 is false.

Here is an example to illustrate this:

.box {
  --a: 1;
  --b: 2;
  --result: calc(var(--a) + var(--b));
  height: calc(var(--result) * 10px);
  border: 1px solid;
}

.alt {
  --a: 2;
}
<div class="box">
 my height is equal to 30px because result is evaluated to 3 (1+2)
</div>

<div class="box alt">
 my height is equal to 40px because result is evaluated to 4 (2+2)
</div>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.