Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I used Mustache to generate some HTML and used insertAdjacentHTML 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 document.querySelector('.contentarea') call. However, if I try to get a pixel value for width or height, it keeps throwing back 'auto'.

Thinking it might just be a problem with getComputedStyle, I tried using .getBoundingClientRect and .offsetWidth instead. Both returned 0. 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.

like image 797
download Avatar asked Dec 25 '11 03:12

download


People also ask

What does the window getComputedStyle () method return?

The Window. getComputedStyle() method returns an object containing the values of all CSS properties of an element, after applying active stylesheets and resolving any basic computation those values may contain.

What are computed styles?

The computed style is the style used on the element after all styling sources have been applied. Style sources: external and internal style sheets, inherited styles, and browser default styles.


2 Answers

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.

like image 173
Robert Hurst Avatar answered Oct 04 '22 12:10

Robert Hurst


In my experience many browsers (IE, Chrome, Firefox) purposefully delay computing layout until after Javascript threads end or yield via a timeout call.

Only solution I know is to yield to the browser and then restart. Your method of using setTimeout works well.

like image 22
Larry K Avatar answered Oct 04 '22 11:10

Larry K