Reputation: 2029
Looking for a simple yet robust way to calculate pixel length from any string such as: "55rem" / "33vh" / "300px" to the current browser in pixels.
From what I understand there is window.getComputedStyle(), but I don't want the style to be attached to any actual element. So, considering I don't care about percentage of any element calculated, just simple unit conversion (relative to the current user browser/zoom) - it should be simple to be reasonably calculated by some pseudo element?
There are some solutions out there involving the actual calculation of the units, yet I believe there must be a simpler 3 liner solution (probably using getComputedStyle or similar function) for this...
Update: Maybe it's not meant to be done in JS. Or simply, not the best practice... That would be an answer too. Just checking on a go/no go for this ...
Upvotes: 0
Views: 3653
Reputation: 13129
getComputedStyle
is a very expensive operation, as it triggers a CSS reflow every time you call it. I'd recommend calculating the conversions by hand, using things like window.innerHeight
or document.body.style.fontSize
(if it's set inline, that is).
If you use Webpack, you can even load SCSS variables to get the body
font-size.
Upvotes: 2