George Robinson
George Robinson

Reputation: 153

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!

Upvotes: 15

Views: 49914

Answers (6)

SwiftNinjaPro
SwiftNinjaPro

Reputation: 851

This worked for me:

document.getElementById().offsetWidth;

Upvotes: 5

Leo
Leo

Reputation: 4438

Maybe

elt.getBoundingClientRect().width

Upvotes: 8

yunyun
yunyun

Reputation: 31

I have experienced like in this post: jQuery width() not returning correct value on a div with generated content. If the div is not displayed earlier or are loading content dynamically, the .width() function returns the percentage value, but till the element is fully loaded the same .width() function will return width in pixels.

Upvotes: 3

Blender
Blender

Reputation: 298402

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

Upvotes: 12

tilleryj
tilleryj

Reputation: 14379

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

Upvotes: 8

&#211;lafur Waage
&#211;lafur Waage

Reputation: 70001

From the jQuery documentation on width()

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). The .width() method is recommended when an element's width needs to be used in a mathematical calculation.

So it returns pixels if the pixel width is defined, but you are defining the width in %

Upvotes: 4

Related Questions