3

Question: Under certain circumstances .getComputedStyle() appears to return an incomplete/incorrect value for the height property of an element. Now I'm worried. Is it known to return unpredictable or incorrect values for other properties?

Backstory: I had been using .getComputedStyle() until I noticed that it was returning what appeared to be incorrect values for the heights of elements. So I tested it against several other methods.

In the simple test code below all of these returned 400 which is the correct height of the element that was tested.

.offsetHeight

.scrollHeight

.clientHeight

.getBoundingClientRect().height

However .getComputedStyle().height returned 300px which is the height of the element before its padding is applied.

'use strict';
 
window.addEventListener('load', measureDiv)
 
function measureDiv() {
  console.log('offsetHeight = ' +document.querySelector('.container').offsetHeight);
  console.log('scrollHeight = ' +document.querySelector('.container').scrollHeight);
  console.log('clientHeight = ' +document.querySelector('.container').clientHeight);
  console.log('getBoundingClientRect().height = ' +document.querySelector('.container').getBoundingClientRect().height);
  console.log('getComputedStyle().height = ' +window.getComputedStyle(document.querySelector('.container')).height);
}
body {
  margin: 0;
  padding: 0;
}
 
.container {
  margin: 120px;
  padding: 50px;
  background-color: green;
}
 
.box_1 {
  padding: 20px;
  background-color: blue;
}
 
.image_container {}
<div class="container">
  
  <div class="box_1">
   
    <div class="image_container"><img src="https://www.cis.rit.edu/~cnspci/courses/common/images/checkerboard-256x256.jpg"></div>
  
  </div>
  
</div>
DR01D
  • 1,325
  • 15
  • 32
  • 3
    That doesn't look incorrect to me; the `height` CSS property does not include the padding or the border unless you've got `box-sizing: border-box;` set. – Pointy Nov 23 '17 at 18:04
  • @Pointy - Mind blown! I just added `box-sizing: border-box;` to the class and sure enough it reported back 400px. I get it now. – DR01D Nov 23 '17 at 18:11
  • @Pointy - FYI I just tested this with `box-sizing: border-box` in IE11 and it still reported a height of 300.14px. But Chrome, Edge and Firefox all reported the correct height. – DR01D Nov 23 '17 at 18:18
  • I'm not sure why IE would get that wrong; perhaps IE is running in one of its weird compatibility modes or quirks mode or something and that throws it off. – Pointy Nov 23 '17 at 18:20
  • IE11 is down to 12.9% according to Analytics.gov https://analytics.usa.gov/ But that's down from just over 52% 2 years ago. Hopefully it will be dead and buried in another 2 years. I hate learning things in 2 ways. – DR01D Nov 23 '17 at 18:42

0 Answers0