How can I convert px to vw in JavaScript?

The formula goes like this

px in vw:

100 * px / windowWidth

px in vh:

100 * px / windowHeight

vh in px:

windowHeight * vh / 100

vw in px:

windowWidth * vw / 100

Some code for inspiration: (I'm a JS noob though)

function viewport_convert(px = 0, vw = 0, vh = 0){
    if(px != 0){
        if(vw){
            return (100 * px / window.innerWidth);
        } else {
            return (100 * px / window.innerHeight);
        }
    } else if(vw != 0 && vh != 0){
        var w_h_arr = [];
        w_h_arr["width"] = Math.ceil((window.innerWidth * vw / 100));
        w_h_arr["height"] = Math.ceil((window.innerHeight * vh / 100));
        return w_h_arr;
    } else if(vw != 0){
        return Math.ceil((window.innerWidth * vw / 100));
    } else if(vh != 0){
        return Math.ceil((window.innerHeight * vh / 100));
    }
}

As 1vw / 1vh represents 1/100th of the viewport width / height, you could achieve this using something like :

var newWidth = yourElement.outerwidth / document.documentElement.clientWidth *100;
yourElement.style.width = newWidth +'vw';

I thought about use a Math.round() to get clean number, but you'll surely get wrong dimensions if you exclude decimals.

Can't you change this values directly in CSS (e.g. with another stylesheet) ? It seems really dirty to convert it via Javascript.

Also, according to Errand's comment, if you simply convert your px to vw/vh, it won't make your current HTML/CSS magically fit in the screen.


1px = (100vw / [document.documentElement.clientWidth] px)

e.g. — If your viewport was 500px wide (equals by definition to 100vw) then

1px = (100vw / 500px) = 0.2vw

I used .clientWidth to exclude any scrollbar from computation