Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find actual rendered values of elements set to 'auto' using JavaScript

Tags:

javascript

dom

Suppose I have the following html, and no CSS

<div> 
  here is some content in this div. it stretches it out
  <br />and down too!
</div>

Now I want to get the actual pixel width and height that the browser has rendered this div as.

Can that be done with JS?

Thank you.

like image 668
doctororange Avatar asked Oct 05 '09 13:10

doctororange


1 Answers

Try getting a reference to your div and reading the offsetWidth and offsetHeight properties:

var myDiv = document.getElementById('myDiv');
var width = myDiv.offsetWidth; // int
var height = myDiv.offsetHeight;

offsetWidth/Height cumulatively measures the element's borders, horizontal padding, vertical scrollbar (if present, if rendered) and CSS width. It's the pixel values of the entire space that the element uses in the document. I think it's what you want.

If that is not what you meant, and you'd rather only the element's width and height (i.e. excluding padding, margin, etc) try getComputedStyle:

var comStyle = window.getComputedStyle(myDiv, null);
var width = parseInt(comStyle.getPropertyValue("width"), 10);
var height = parseInt(comStyle.getPropertyValue("height"), 10);

The values above will be the final, computed pixel values for the width and height css style properties (including values set by a <style> element or an external stylesheet).

Like all helpful things, this won't work in IE.


You say you are using jQuery. Well it's trivial now, and works cross-browser:

var width = $('div').css('width');
var height = $('div').css('height');

With jQuery you don't need the first part of this answer, it's all taken care of for ya ;)

like image 52
Roatin Marth Avatar answered Nov 05 '22 07:11

Roatin Marth