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
Width from .width()
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.
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.
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 ).
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.
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).
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...
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