Skip to content
Advertisement

Rem units in JS are calculated?

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`

Advertisement

Answer

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>
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement