download download - 10 months ago 41
Javascript Question

Why does getComputedStyle return 'auto' for pixels values right after element creation?

I used Mustache to generate some HTML and used

to place it on the page. It apparently converted to a DOM structure alright since I can get a handle to it afterwards by using a
call. However, if I try to get a pixel value for width or height, it keeps throwing back

Thinking it might just be a problem with
, I tried using
instead. Both returned
. It works if I delay the call slightly by placing it inside a
setTimeout(function(){}, 1)
, but that's not practical for my production code since it needs to go inside a synchronous constructor.

This is happening in both Firefox (Aurora), and Chrome.
I remembered reading an article on how Mozilla improved DOM manipulation performance by using lazy frame construction and thought there might be a bug with the frames being a little too lazy, but since it's happening in Chrome as well, that seems less likely.

Does anyone have any ideas about what's going on here or how to work around it? I really need the pixel height/width information immediately after inserting the HTML.

PS: Do any browsers do the HTML to DOM parsing/building in a separate thread? I was thinking that might cause this sort of behavior as well.

NEVERMIND: It was my own fault. I just didn't notice a
display: none;
style that was set before the code tried to get the measurements.

Answer Source

There are a couple of things that can cause a result of "auto". You found one of them; display: none. If an element is inline it will also return auto.

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