Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the actual, floating-point width of an element

I'm using jQuery (v1.7.1) and I need to get the absolute, floating-point width of an element, but all of jQuery's width methods seem to be rounding-off the value of the width.

For example if the actual width of an element was 20.333333px, jQuery's width method returns 20, i.e ignoring the decimal value.

You can see what I mean on this jsFiddle

So, my question is: How do I get the floating-point value of the width of an element?

like image 546
S P Avatar asked Aug 10 '12 18:08

S P


People also ask

How do you find the width of an element?

Use offsetWidth & offsetHeight properties of the DOM element to get its the width and height.

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.

Which method returns the width of an element?

The outerWidth() method returns the width of an element (includes padding and border).

What is element width?

The width property in CSS specifies the width of the element's content area. This “content” area is the portion inside the padding, border, and margin of an element (the box model). .wrap { width: 80%; } In the example above, elements that have a class name of . wrap will be 80% as wide as their parent element.


1 Answers

If you already have a reference to the DOM element, element.getBoundingClientRect will get you the values you want.

The method has existed since Internet Explorer 4, and so it's safe to use everywhere. However, the width and height attributes exist only in IE9+. You have to calculate them if you support IE8 and below:

var rect = $("#a")[0].getBoundingClientRect();  var width; if (rect.width) {   // `width` is available for IE9+   width = rect.width; } else {   // Calculate width for IE8 and below   width = rect.right - rect.left; } 

getBoundingClientRect is 70% faster than window.getComputedStyle in Chrome 28, and the differences are greater in Firefox: http://jsperf.com/getcomputedstyle-vs-getboundingclientrect

like image 144
Ross Allen Avatar answered Oct 10 '22 09:10

Ross Allen