jQuery - find out the width of an element as specified in CSS (e.g. in %age if it was specified in %age, not just in px)

vitch picture vitch · Aug 21, 2010 · Viewed 14.3k times · Source

Similar to this question: get CSS rule's percentage value in jQuery

However, I am writing a plugin and it needs to deal with it gracefully dependent on how the width was originally specified. If the element was originally specified in pixels it is fine as that is the value that .width(), .innerWidth(), outerWidth() and .css('width') return.

But I want to know if it was original set as a percentage. So that if the container element resizes then I know to recalculate the width that I have set on my element.

Is this possible? The only thing I can think of is trying to loop through document.stylesheets looking for relevant rules but I think that will be more or less impossible to do generically. Any other ideas?

Thanks!

Answer

data picture data · Aug 21, 2010

It seems like .css('width') works for me.

Small example to show this works:

<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>

<div style="width:10%;" id="foo"></div>
<script>
alert($("#foo").css('width'));
</script>

</body>
</html>

This gives me an output of "10%". Hope I didn't miss anything obvious.