0

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 ...

rubmz
  • 1,947
  • 5
  • 27
  • 49
  • Could you please clarify this: `but I don't want the style to be attached to any actual element`? – GrafiCode Jun 10 '19 at 08:42
  • 1
    It has to be `attached to any element` since `em`, for example, depends on the elements font size. – Roberto Zvjerković Jun 10 '19 at 08:44
  • anyway, you can use properties `.clientWidth` and `.clientHeight` – GrafiCode Jun 10 '19 at 08:44
  • What is the intended use for the calculated value, will it be used to set the size of some element? If so, maybe the [CSS calc() function](https://developer.mozilla.org/en-US/docs/Web/CSS/calc) can do what you need? – kristaps Jun 10 '19 at 09:06
  • I mean only the simple sizes... rem, vh, vw, px. Not em, or at least not a specific element (html body would do...). – rubmz Jun 10 '19 at 09:18

1 Answers1

2

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.

Ruben Helsloot
  • 12,582
  • 6
  • 26
  • 49