Qwertiy
Qwertiy

Reputation: 21400

Convert rem to px without reflow

I have some constant in rems, but rem itself isn't a constant (depends on media queries and vmin). For some perpoise I need this value in px.

Of course I can create a temporary div, set its size to that value in rem and getComputedStyle of it to get value in px. But I'd like to do that without causing a reflow by reading the computed style.

Upvotes: 8

Views: 7943

Answers (2)

Mark
Mark

Reputation: 92440

A rem unit equal to the computed value of ‘font-size’ on the root element. (https://www.w3.org/TR/2013/CR-css3-values-20130730/#font-relative-lengths)

You can get that easily enough with 1 rem =

parseInt(getComputedStyle(document.documentElement).fontSize)

Upvotes: 13

maioman
maioman

Reputation: 18734

By definition rem is

Equal to the computed value of font-size on the root element.
When specified on the font-size property of the root element,
the rem units refer to the property’s initial value.

So you should be able to get it's size with:

window.getComputedStyle(document.documentElement)['font-size']

Upvotes: 0

Related Questions