Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rem px in Javascript

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.

like image 997
Malus Jan Avatar asked Apr 10 '16 16:04

Malus Jan


People also ask

What Is rem in Javascript?

To recap, the rem unit means "The root element's font-size" (rem stands for "root em"). The <li> elements inside the <ul> with a class of rems take their sizing from the root element ( <html> ).

Can you use rem in Javascript?

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.

What Is rem in px?

1 rem = 16 pixels. So all you have to do is divide the units of your design in pixels by 16. For example, a font that was 32 pixels in size becomes: 2 rem. 32 (px) /1 6 = 2 (rem)


2 Answers

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

like image 168
etham Avatar answered Oct 17 '22 13:10

etham


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

like image 22
Quentin Avatar answered Oct 17 '22 13:10

Quentin