How to get element width in pixels (px)? jQuery always returns value in percent (pct).
HTML
<span class="myElement"></span>
CSS
.myElement {
float: left;
width: 100%;
height: 100%;
}
JavaScript
$('span.myElement').css('width') // returns '100%'
$('span.myElement').width() // returns '100'
Thanks!
The offsetWidth property returns the viewable width of an element (in pixels) including padding, border and scrollbar, but not the margin. The offsetWidth property is read-only.
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.
If you need to know the total amount of space an element occupies, including the width of the visible content, scrollbars (if any), padding, and border, you want to use the HTMLElement. offsetWidth and HTMLElement. offsetHeight properties. Most of the time these are the same as width and height of Element.
offsetWidth , offsetHeight : The size of the visual box incuding all borders. Can be calculated by adding width / height and paddings and borders, if the element has display: block. clientWidth , clientHeight : The visual portion of the box content, not including borders or scroll bars , but includes padding .
How many items have the class myElement
? Consider using an id
, not a class
, as getting the width of two elements is not really possible (or logically understandable IMO).
I made a little demo, and for me, it outputs the width in pixels for a single span
element with a width of 100%
(for me, it alerts something around 400
): http://jsfiddle.net/LqpNK/3/.
By the way, <span>
element's can't have a set width or height, so setting their width and height does you no good. Instead, display them as a block
element (so just replace <span>
with <div>
, or add display: block;
to the CSS of .myElement
).
.css('width') should return 100%, however .width() should (as described here http://api.jquery.com/width/) return a unit-less pixel amount. I created a jsfiddle to demonstrate: http://jsfiddle.net/yxCav/
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