55

I use this code in JS:

bigPhoto.setAttribute("width", "200rem");

The result is in pixel in html source,

enter image description here

But:

enter image description here

When I change it to 20rem the photo become really small.

I couldn't solve the problem which is mentioned in the photos.

t3ol5
  • 94
  • 7
Malus Jan
  • 1,860
  • 2
  • 22
  • 26
  • Do you mean `rem` or `em` ? –  Apr 10 '16 at 16:25
  • 1
    The inspector will always show pixel width - that doesn't mean that you haven't specified `rem`. Apparently, your base font size is `10px` so that `20rem = 200px` – Adam Jenkins Apr 10 '16 at 16:28
  • 2
    rem: relative em. rem is depend on device and it is suggested to use if the website is for any different devices with different density. for the project that I should write, I am supposed to use DOM so I used JS to set the width but rem in js doesn't work . We couldn't tell that 20rem = 200px in all devices. – Malus Jan Apr 10 '16 at 16:55

2 Answers2

246

Another method would be to convert rem into pixels:

function convertRemToPixels(rem) {    
    return rem * parseFloat(getComputedStyle(document.documentElement).fontSize);
}

This can be useful when you must perform some arithmetic in js (such as using the position of the mouse to display a tooltip...)

etham
  • 3,158
  • 2
  • 16
  • 13
  • 4
    This is a great answer. `getComputedStyle` is supported also by IE11 – keul Dec 20 '19 at 10:45
  • 1
    i used hidden element to calc 1 rem, but this answer is great – Dee Mar 16 '21 at 13:30
  • 1
    Very useful! Small nitpick: Casting the input `rem` with `parseFloat(rem)` would also allow for a value that contains the `rem` unit in it. – Julien Aug 26 '21 at 15:55
  • Thanks. I could get the rem information on a webpage. By entering "getComputedStyle(document.documentElement).fontSize" in the console of developer tools. And you can get the rem in Px. – Alf Bae Feb 08 '22 at 08:55
  • @Julien It would only parse the number portion of the string '123rem', as 123, not to calculate how much each rem unit is in px. – David Min Feb 09 '22 at 17:22
  • Is there equivalent for Node.js? – Ali EXE Jun 03 '23 at 13:52
13

The HTML width attribute only takes an integer number of pixels or a percentage (followed by a % sign).

If you wish to use CSS length units you have to use CSS (and set bigPhoto.style.width = "200rem".

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335