stecb stecb - 1 year ago 53
Javascript Question

Retrieving percentage CSS values (in firefox)

I have a problem retrieving the exact css property value (in '%') on firefox.

Suppose we have this extremely simple markup:

<div id="box">box</div>

and this css:


and I'd like to retrieve the left position (in '%') by js

It's obv very easy with mootools (demo ->

var left = $('box').getStyle('left');

or jQuery (demo ->

var left = $('#box').css('left');

or by plain js (demo ->

function getStyle(el,styleProp){ //from ppk's quirksmode
var x = document.getElementById(el);
if (x.currentStyle)
var y = x.currentStyle[styleProp];
else if (window.getComputedStyle)
var y = document.defaultView.getComputedStyle(x,null).getPropertyValue(styleProp);
return y;

var left = getStyle('box','left');

But if you try it on firefox (8.0.1) you'll see that the result is not correct (should be 10%, but it's 91px). The questions are: is there a bug on this newer version of firefox? Does anyone knows if it's a known bug? Am I doing something wrong?

Thanks :)

Update: I tried it also on older firefox releases, and it's not correct (it always returns px value).. for completeness, it works correctly on IE

Answer Source

The correct answer is a comment on the bug I filed on bugzilla

To get the correct % value (on firefox too) the element's (or one of its parents) display should be set to none

Test :

The unclear thing is: why on the same browser/version (see, firefox 7 on XP/win7 or Opera 11.5 on mac osx / ubuntu) but on different os, the behav is different?

Btw, the spec @thg435 posted (and reported on mdn) is still in flux.