Naheed
Naheed

Reputation: 51

How to get CSS height and width if they are in percentage value using JavaScript?

How to get CSS height and width if they are in percentage value using JavaScript?

Lets say the CSS rule:

.field {
  height:50%;
  width:25%;
}

What we tried:

let a = document.getElementById("field");
console.log(a.style.height)

This give me empty string. Is there any way to get height in percentage using JavaScript?

Upvotes: 1

Views: 1591

Answers (3)

A Haworth
A Haworth

Reputation: 36492

The height of an element a as a percentage of its parent can be calculated as

getComputedStyle(a).height.replace('px','') / getComputedStyle(a.parentElement).height.replace('px','') * 100 + '%'

This works however the styles of a and its parent have been set (through classes, through inline style setting). It is not the same as finding out whether the heights were set by a percentages or by other units initially.

Here's a simple example:

let a = document.querySelector(".field");

console.log(getComputedStyle(a).height.replace('px','') / getComputedStyle(a.parentElement).height.replace('px','') * 100 + '%');
.container {
  height: 50vh;
  width: 30vw;
}

.field {
  height:50%;
  width:25%;
}
<div class="container">
  <div class="field"></div>
</div>

Upvotes: 2

Dr M L M J
Dr M L M J

Reputation: 2397

in css rule,field is with dot = class and in js, you are trying getElelmentById.

Change .field to #field in css rule and try ...

#field{
   height:50%;
   width:25%;
 }

You can use getComputedStyle

 let elem = document.getElementById('field');
 let ht = window.getComputedStyle(elem, null).getPropertyValue("height");
 console.log(ht)

Upvotes: 0

kamalnath
kamalnath

Reputation: 56

Height = a.offsetHeight Width = a.offsetWidth This gives height and width in pixels. Doesn't matter how it's declared in CSS.

Upvotes: 1

Related Questions