Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use jQuery to get the width of an element in percent or pixels, based on what the developer specified with CSS?

Tags:

jquery

css

width

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?

like image 370
joren Avatar asked Oct 23 '10 23:10

joren


People also ask

How do you find the width of an element in pixels?

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.

What is width percentage CSS?

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 .

How does jQuery width work?

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).


2 Answers

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; 
like image 94
Matt Ball Avatar answered Sep 21 '22 17:09

Matt Ball


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.

like image 28
timofey.com Avatar answered Sep 22 '22 17:09

timofey.com