Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get element width in px

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!

like image 625
George Robinson Avatar asked Apr 02 '11 18:04

George Robinson


People also ask

How do you find the width of an element?

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.

How do I 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.

How do I get the size of an element in HTML?

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.

How is offsetWidth calculated?

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 .


2 Answers

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

like image 65
Blender Avatar answered Sep 30 '22 14:09

Blender


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

like image 27
tilleryj Avatar answered Sep 30 '22 15:09

tilleryj