I'm writing a jQuery plugin and something I need to be able to do is determine the width of an element that the user specifies. The problem is that .width() or .css('width') will always report exact pixels, even if the developer has assigned it e.g. width:90% with CSS.
Is there any way to have jQuery output the width of an element in px or % depending on what the developer has given it with CSS?
To get the width of a specific HTML Element in pixels, using JavaScript, get reference to this HTML element, and read the clientWidth property of this HTML Element. clientWidth property returns the width of the HTML Element, in pixels, computed by adding CSS width and CSS padding (top, bottom) of this HTML Element.
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() and height() MethodsThe width() method sets or returns the width of an element (excludes padding, border and margin). The height() method sets or returns the height of an element (excludes padding, border and margin).
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.
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