Why does window.getComputedStyle() show discrepancies in value for width and height?

Viewed 36

I am having a pretty simple few lines to determine the computed width and height of a DOM element. Or so I thought:

const computedStyle = window.getComputedStyle(element, null);
// const width = computedStyle.getPropertyValue('width');
const width = computedStyle['width'];
console.log(width); // 'auto'
console.log("computed", computedStyle);

However, when I log the value for width, I am getting 'auto', no matter if I access it directly as a property or through the getPropertyValue getter. But when I just check the value in the log of the entire computedStyle object, I am getting the following:enter image description here which is clearly not the same.

What is the problem here? Does it have to do with the dynamic nature of getComputedStyle, aka is 'auto' the initial value (the above lines get called in the componentDidRender lifecycle event of a Stencil web component) and the width on computedStyle actually was updated after being shown initially?

2 Answers

The object printed in browser console will be dynamically updated into latest value when you first expand it.

For example, consider the following one line code

const foo = {bar: 0}; console.log(foo); foo.bar = 1;

There will be an object {bar: 0} printed in the console. However, when you try to expand it in the console, it will show bar: 1 under it.

So apply this in your case, computedStyle.width is "auto" immediately after logging. But before you expand it in console, the browser did some calculation and it is changed into "111.234px".

The Stencil lifecycle hook to use was componentDidUpdate, this gets fully rendered components (although the manual says componentDidLoad should, too), and just to make sure I don't have anything dynamic going on and get the coordinates for free, I used element.getBoundingClientRect() in place of getComputedStyle. So, I guess, one could say this solves my particular problem, although it does not really feel like a solution, more like a workaround...

Related