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!
As an example, if the element has width: 100px; and transform: scale(0.5); the getBoundingClientRect() will return 50 as the width, while offsetWidth will return 100.
The <percentage> CSS data type represents a percentage value. It is often used to define a size as relative to an element's parent object. Numerous properties can use percentages, such as width , height , margin , padding , and font-size .
jQuery width() Method The width() method sets or returns the width of the selected elements. When this method is used to return width, it returns the width of the FIRST matched element. When this method is used to set width, it sets the width of ALL matched elements.
width: 100%; will make the element as wide as the parent container. Extra spacing will be added to the element's size without regards to the parent.
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.
I couldn't find a way to do what I asked for in the question but I came up with a workaround which allows me to do what I need to in my situation. The code in question is for my jQuery plugin called jScrollPane ( http://jscrollpane.kelvinluck.com/ ). In the end what I do is set the width to null (elem.css('width', null);
). This removes the width I had set myself previously and allows the element to take it's natural width as defined in the stylesheet (i.e. using a percentage if that's how it was defined). I can then measure this new value and use that to set the width to the number I desire...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With