1
const someHeight = "3rem";
example.style.padding = `calc(${someHeight} + 2rem)`;

Results in the inline style of: padding: calc(5rem).

My expected result is: padding: calc(3rem + 2rem).

It seems the result of calc() is calculated by JS. Why is this happening? And if JS can add two rem values, why doesn't this work?

example.style.padding = `${someHeight} + 2rem`
Dirk J. Faber
  • 4,360
  • 5
  • 20
  • 58

1 Answers1

2

It seems the result of calc() is calculated by JS.

Not by the JavaScript code, no; by the browser. The style object is not a simple container. When you assign to properties on it, the browser processes those and when you look at their values, those are not necessarily in the same form as when you assigned them. For instance, if you do example.style.color = "#020202" and then look at example.style.color, you're likely to see rgb(2, 2, 2) or similar (it varies by browser):

const example = document.getElementById("example");
example.style.color = "#020202";
console.log(example.style.color); // rgb(2, 2, 2) on Chrome
<div id="example"></div>

This is the same sort of thing, if you assign calc(3rem + 2rem), since those units are the same, it's not surprising that when giving the value back to you, the browser has combined them:

const example = document.getElementById("example");
example.style.padding = "calc(3rem + 2rem)";
console.log(example.style.padding); // calc(5rem) on Chrome
<div id="example"></div>

You can see that it's not the JavaScript code that's doing it by writing the result to a variable:

const example = document.getElementById("example");
const someHeight = "3rem";
const padding = `calc(${someHeight} + 2rem)`;
console.log(padding);               // calc(3rem + 2rem)
example.style.padding = padding;
console.log(example.style.padding); // calc(5rem) on Chrome
<div id="example"></div>
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • This makes sense! The only thing that still surprises me is that the processing by the browser is only successful when the units are wrapped in `calc()`. – Dirk J. Faber Feb 24 '21 at 13:05
  • 1
    @DirkJ.Faber - That's the only place they're valid. `3rem + 2rem` isn't a valid length value, but `calc(3rem + 2rem)` is. :-) – T.J. Crowder Feb 24 '21 at 13:15