admin管理员组

文章数量:1404923

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.

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.

Share Improve this question edited Aug 18, 2013 at 15:21 Cody Gray 245k53 gold badges504 silver badges585 bronze badges asked Aug 18, 2013 at 15:02 MattijsMattijs 3722 gold badges4 silver badges13 bronze badges 5
  • 1 Can you not just replace 640 with "70%"? – Ian Clark Commented Aug 18, 2013 at 15:04
  • Try using: stackoverflow./questions/3437786/… to get the current size, and multiply that by whatever percentage you want. – Gal Commented Aug 18, 2013 at 15:04
  • Gal, could i get an example? – Mattijs Commented Aug 18, 2013 at 15:10
  • and no i cannot just use '70%' – Mattijs Commented Aug 18, 2013 at 15:11
  • This may be out of date, but I had success using '70vh' instead of '70%' – SeanVDH Commented Sep 18, 2014 at 0:09
Add a ment  | 

3 Answers 3

Reset to default 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 plex approach to determine the viewport size for cross-browser support however, but this question was already answered.

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%

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%;
}

本文标签: Setting width and height as a percentage in JavaScriptStack Overflow