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>