Why does getComputedStyle return "auto" for pixel values ​​immediately after creating an element?

I used Mustache to create some HTML and used insertAdjacentHTML to place it on the page. Apparently, it is being converted to a DOM structure, since after that I can handle it with a call to document.querySelector('.contentarea') . However, if I try to get the pixel value for width or height, it will cast back 'auto' .

Thinking this might be a problem with getComputedStyle , I tried using .getBoundingClientRect and .offsetWidth . Both returned 0 . It works if I delayed the call a bit by placing it inside setTimeout(function(){}, 1) , but this is not practical for my production code, since it needs to go into the synchronous constructor.

This happens both in Firefox (Aurora) and in Chrome. I recalled reading an article about how Mozilla improved the performance of DOM manipulation using a lazy frame design, and thought there might be a bug with frames that are a bit lazy, but since this also happens in Chrome, this seems less likely.

Does anyone have any ideas on what's going on here or how to get around? I really need information on the height and width of the pixel right after pasting the HTML.

PS: Do any browsers make HTML to parse / create the DOM in a separate thread? I thought this could cause similar behavior.

NEVERMIND: It was my own mistake. I just did not notice the display: none; style display: none; that was installed before the code tried to get the measurements.

+7
source share
2 answers

There are a few things that can cause an "auto" result. You have found one of them; display: none . If the item is inline, it will also return automatically.

Essentially, it must be a block or inline-block element, and it must be rendered.

+8
source

In my experience, many browsers (IE, Chrome, Firefox) deliberately delay the calculation of the layout until the Javascript threads end or exit through a timeout.

The only solution I know is to succumb to the browser and then restart. Your method of using setTimeout works well.

0
source

All Articles