Saturday, August 20, 2011

JavaScript's window.getComputedStyle() method is safe, right?

WRONG!

Its output can and will differ from browser to browser.

I encountered this because I was trying to fix my image script's in-page popups so that they appear in the correct area of the screen.  I have code that's supposed to center them both horizontally and vertically, but they have padding around the edges that throws this calculation off.  So the fix would be to get the size of the padding on each side in pixels (to account for browser rendering differences), add those values to the width and height (respectively), then position the box with my already existing code and the new width and height values.

As it turns out, the values returned by the window.getComputedStyle() method are mostly similar in standards-compliant browsers, so long as the element exists within the DOM.  But what if, like me, you're trying to position it correctly before inserting it, and thus need the padding value before the element is visible?

You get all kinds of crazy shit.  Ideally the same value should be returned in both cases, but unfortunately this is far from the truth.

I could mention some sample output here, but an example test you can run in multiple browsers is better.  Fortunately for you, I've made such a test.

Now of course an easy workaround is to temporarily apply display: none; to the element, insert it into the DOM, correct its position, and then set it back to display: block; or whatever, but I shouldn't have to do that.

By the way, if anyone from the W3C so happens to be reading this, CSS really needs a box-align selector, to let you align element boxes themselves relative to the browser viewport.  It would be shorthand for box-align-vertical and box-align-horizontal, which would accept percentages as well as "center" as a value, and user-agents would try their best to align the center of each side according to the specified style.  That way, we wouldn't be dependent on buggy and inconsistent implementations of getComputedStyle() to position something relative to the viewport and keep it there.

No comments:

Post a Comment

I moderate comments because when Blogger originally implemented a spam filter it wouldn't work without comment moderation enabled. So if your comment doesn't show up right away, that would be why.