Search code examples
javascriptcssviewportviewport-units

How to calculate a number and turn it into vw or vh?


I am relatively new to programming and I've run into a problem. I want to calculate a number and turn it into a viewport unit.

The calculation I am trying to do is 100 / height * width and the number that comes out of this equation should be in a viewport unit. Width and height are pre-defined variables in my code I have tried putting the equation in all types of brackets, I have tried putting the viewport unit inside of the equation like this: 100vw / width = height. But everything gives me an error.

The full part:

if (h / height > w / width) {
   container.style.width = [100 / width * height]vw;
   container.style.height = 100vw;
}
container.style.width = [100 / width * height]vw;

and

container.style.width = 100vw / width * height;

Please let me know if this is possible in javascript. I am not familiar with jquery so jquery answers won't help me. I am open to learning how to calculate something like this in css, but I don't know how I would implement an if statement than. Thanks in advance!


Solution

  • Assuming your width and height variables contain numbers, do the math first, then append the string "vw":

    container.style.width = (100 / width * height) + "vw"