1

Here is my JavaScript code:

a.width = a.width ? a.width : 640;
a.height = a.height ? a.height : 360;

How can I make the 640px and 360px percentages instead? I want them both to be 70% of the windows size.

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
Mattijs
  • 195
  • 2
  • 3
  • 12

3 Answers3

1

If the container of the element have sizing specified already, then you can simply use percentages in CSS. For instance:

.#my-el {
    width: 70%;
    height: 70%;
}

<div id="my-el"></div>

However, if you have to use JavaScript for some reason, you could do something like:

el.style.width = Math.round(document.documentElement.clientWidth * .70) + 'px';

You may have to use a more complex approach to determine the viewport size for cross-browser support however, but this question was already answered.

plalx
  • 42,889
  • 6
  • 74
  • 90
1

percentage is a relative value.

you need to have relative value like screenWidth (for suppose) 1240px so that you will get percentage of that value.

Example

var pixels = 100;
var screenWidth = window.screen.width;
var percentage = ( screenWidth - pixels ) / screenWidth ; // 0.92%
Amith
  • 1,424
  • 1
  • 10
  • 22
0

To set an element's width or height as a percentage, there are a couple of options available.

Firstly, you can set the element's dimensions as a percentage of its container like this:

element.width = "70%";
element.height = "70%";

Alternatively, you can set the dimensions as a percentage of the screen size instead like this:

element.width = "70vw";
element.height = "70vh";

These values stand for "viewport height" and "viewport width".

However, since both of these options use basic CSS values, it may be preferable to add a CSS class dynamically to the element instead of setting its style properties directly in JavaScript. For example:

element.classList.add("my-class");

Then, define the .my-class selector in a stylesheet like this:

.my-class {
  width: 70%;
  height: 70%;
}
Mattijs
  • 195
  • 2
  • 3
  • 12