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)
    });
});
2
  • There was a very closely related question today: stackoverflow.com/questions/4105355 Read @bobince's answer for some background Commented Nov 5, 2010 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? Commented Nov 5, 2010 at 20:39

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

You need to read the stylesheet itself.

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

Comments

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.

2 Comments

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: martinsmucker.com/demo/ie_shadow2.html). :-/ This is a very helpful thing to know, though, thanks!
This is also in pixels, not actual CSS value if is 100% for example

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.