3

I'm trying to calculate the width of an element so that when I use JavaScript to wrap a parent element around it, I can set the width of the parent to match the width of the child. The obvious $('#element').css('width'); isn't quite what I want because it only seems to return the calculated value in pixels. Is there some way that I can return the actual CSS value, whether it be 300px or 20% or auto, instead of the calculated value?

Here's generally how it's set up, but I'd like to know the CSS value of #child instead of the calculated value.

$(document).ready(function(){
    $('#child').wrap('<div id="parent"></div>');
    $('#parent').each(function(){
        var childWidth = $(this).children('#child').css('width');
        $(this).css('width', childWidth)
    });
});
Michael Martin-Smucker
  • 11,927
  • 7
  • 31
  • 36
  • There was a very closely related question today: http://stackoverflow.com/questions/4105355 Read @bobince's answer for some background – Pekka Nov 05 '10 at 20:38
  • Do you want to get the width property of the `style` attribute on the element, or also settings defined in CSS classes? – Pekka Nov 05 '10 at 20:39

3 Answers3

2

I don't believe you can do that. The best you will get is offsetWidth or clientWidth which return the calculated value, with and without counting margins, padding and borders.

josh.trow
  • 4,861
  • 20
  • 31
0

You need to read the stylesheet itself.

See: How can I read out the CSS text via Javascript as defined in the stylesheet?

Community
  • 1
  • 1
Diodeus - James MacFarlane
  • 112,730
  • 33
  • 157
  • 176
0

Everyone but IE supports window.getComputedStyle(element), which you can use like so:

getComputedStyle($('#child')).width; // returns actual width of #child

Doesn't help you with IE, though.

Robusto
  • 31,447
  • 8
  • 56
  • 77
  • Piss. The whole reason I was doing this was so that I could put a blur filter on the parent element "if lte IE 8" to mimic the CSS3 box-shadow look (see: http://martinsmucker.com/demo/ie_shadow2.html). :-/ This is a very helpful thing to know, though, thanks! – Michael Martin-Smucker Nov 05 '10 at 20:53
  • This is also in pixels, not actual CSS value if is 100% for example – Adrian B Aug 27 '21 at 05:12