Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.width() function is not returning correct value

Tags:

html

jquery

I am trying to dynamically access the width of an element through jQuery using .width(). In developer tools I can see element's width as 37.333Px, where as .width() gives 38.33334Px.

Width in developer tools

enter image description here

Width from .width()

enter image description here

In this situation difference is of 1px, but sometimes it difference is in decimals. Why there is a such difference? Where am I going wrong? Is there any other to get exact width.

like image 439
Kusuma Avatar asked Feb 11 '16 08:02

Kusuma


People also ask

What does .CSS width and width () change the width of?

The width CSS property sets an element's width. By default, it sets the width of the content area, but if box-sizing is set to border-box , it sets the width of the border area.

What is the difference between width () vs CSS width in jQuery?

The difference between . css( "width" ) and . width() is that the latter returns a unit-less pixel value (for example, 400 ) while the former returns a value with units intact (for example, 400px ).

How do you find the width of a div?

To measure the width of a div element we will utilize the offsetWidth property of JavaScript. This property of JavaScript returns an integer representing the layout width of an element and is measured in pixels. Return Value: Returns the corresponding element's layout pixel width.


2 Answers

We can get width by few methods listed below,

width() - Sets or returns the width of an element

innerWidth() - Returns the width of an element (includes padding)

outerWidth() - Returns the width of an element (includes padding and border).

outerWidth(true) - Returns the width of an element (includes padding, border and margin).

enter image description here

enter image description here

like image 120
Anil Kumar Ram Avatar answered Sep 18 '22 08:09

Anil Kumar Ram


Use .width() only when DOM is ready to give you the exact value. Since it takes time to adjust itself while parsing.

So You need to use $(document).ready(... or $(window).load...

like image 20
Amar Singh Avatar answered Sep 19 '22 08:09

Amar Singh