how do i retrieve an html elements actual width and height

how do i retrieve an html elements actual width and height  using -'javascript,html,xhtml,dhtml'

Suppose that I have a <div> that I wish to center in the browser's display (viewport). To do so, I need to calculate the width and height of the <div> element. What should I use for maximum browser compatibility? Looking for a solution that works on IE6+, FF2+, Opera and Webkit-based browsers (Safari 3+, Google Chrome).

asked Oct 11, 2015 by akhilesh
0 votes

7 Answers

0 votes

You should use the .offsetWidth and .offsetHeight properties. Note they belong to the element, not .style.

var width = document.getElementById('foo').offsetWidth;

answered Oct 11, 2015 by akasati02
0 votes

As of jQuery 1.2.6 you can use one of the core CSS functions, height and width (or outerHeight and outerWidth, as appropriate).

var height = $("#myDiv").height();
var width = $("#myDiv").width();

var docHeight = $(document).height();
var docWidth = $(document).width();
answered Oct 11, 2015 by rolvyrf
0 votes

You only need to calculate it for IE7 and older (and only if your content doesn't have fixed size). I suggest using HTML conditional comments to limit hack to old IEs that don't support CSS2. For all other browsers use this:


This is the perfect solution. It centers

of any size, and shrink-wraps it to size of its content.

answered Oct 11, 2015 by sameer rathore
0 votes

... seems CSS help to put div on center ...

... so you hav div 200px*100px on center ...
answered Oct 11, 2015 by ukohale
0 votes

element.offsetWidth and element.offsetHeight should do, as suggested in previous post.

However, if you just want to center the content, there is a better way of doing so. Assuming you use xhtml strict DOCTYPE. set the margin:0,auto property and required width in px to the body tag. The content gets center aligned to the page.

answered Oct 11, 2015 by abhi
0 votes

Take a look at Element.getBoundingClientRect().

This method will return an object containing the width, height, and some other useful values:

    width: 960,
    height: 71,
    top: 603,
    bottom: 674,
    left: 360,
    right: 1320

I believe this does not have the issues that .offsetWidth and .offsetHeight do where they sometimes return 0 (as discussed in the comments here)

Note: getBoundingClientRect does not return height and width on <= IE8.

answered Oct 11, 2015 by girisha
0 votes

If offsetWidth returns 0, you can get element's style width property and search it for a number. "100px" -> 100


answered Oct 11, 2015 by devkumargupta