Is it possible to use jQuery to get the width of an element in percent or pixels, based on what the developer specified with CSS?

I'd say the best way is to compute it yourself:

var width = $('#someElt').width();
var parentWidth = $('#someElt').offsetParent().width();
var percent = 100*width/parentWidth;

It's most definitely possible!

You must first hide() the parent element. This will prevent JavaScript from calculating pixels for the child element.

$('.parent').hide();
var width = $('.child').width();
$('.parent').show();
alert(width);

See my example.


I think you can use stylesheet ('style') object access directly. Even then, YMMV by browser. e.g. elm.style.width.

Edit for Peter's comment:: I am not looking to 'get a %'. As per the question:

I need to be able to do is determine the width of an element that the user specifies ... [is there a way to] output the width of an element in px or % depending on what the developer has given it with CSS?

Thus I provided an alternative to retrieve the "raw" CSS value. This appears to work on FF3.6. YMMV elsewhere (netadictos's answer may be more portable/universal, I do not know). Again, it is not looking to 'get a %'.


The way to do it is documented in this stackoverflow question.

How do you read CSS rule values with JavaScript?

The only thing you have to know is in which stylesheet is the class or loop through all the stylesheets. The following function gives you all the features of the class, it would be easy to do a regex to extract the feature you look for.

function getStyle(className) {
    var classes = document.styleSheets[0].rules || document.styleSheets[0].cssRules
    for(var x=0;x<classes.length;x++) {

        if(classes[x].selectorText==className) {
                (classes[x].cssText) ? alert(classes[x].cssText) : alert(classes[x].style.cssText);
        }
    }
}
getStyle('.test');

For my purposes I extrapolated off MДΓΓ БДLL's answer.

Keep in mind, I'm only working with whole percentages.

    var getPercent = function(elem){
        var elemName = elem.attr("id");
        var width = elem.width();
        var parentWidth = elem.offsetParent().width();
        var percent = Math.round(100*width/parentWidth);
        console.log(elemName+"'s width = "+percent+"%");
    }

    getPercent($('#folders'));
    getPercent($('#media'));
    getPercent($('#player'));