Search code examples
javascriptheightpaddinggetpropertyvalue

Javascript - getPropertyValue gives wrong height


let a = document.getElementsByClassName("d1");
let b = window.getComputedStyle(a[0]);
let c = b.getPropertyValue("height");
alert(c);
.d1 {
  background-color: red;
  padding: 20px;
}
<div class="d1">Test test test</div>

The above code alerts 18px but the height of the div element is actually 48px. It looks like that it doesn't take in consideration its padding. How can I alert its real height?


Solution

  • The CSS height property does not include padding. Try using .clientHeight instead, which does include padding. Here's from the docs:

    clientHeight can be calculated as: CSS height + CSS padding - height of horizontal scrollbar (if present).

    let a = document.getElementsByClassName("d1");
    let c = a[0].clientHeight;
    alert(c);
    .d1 {
      background-color: red;
      padding: 20px;
    }
    <div class="d1">Test test test</div>