views:

2918

answers:

6

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

+1  A: 

Jquery dimensions plugin.

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

var docHeight = $(document).height();
var docWidth = $(document).width();
tvanfosson
is there a way to do it without jQuery?
warren
Of course, jquery uses native javascript to do it. Download the plugin and look at the code if you want to do it yourself. However, you said what should I use for maximum browser compatibility? -- jquery is your friend.
tvanfosson
Prototype has getHeight() and getWidth(), if you prefer that.
tvanfosson
I'm actually using MochiKit for this project, so jQuery isn't an option (yet).
smerp
+6  A: 

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

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

Greg
Beware! offsetHeight/offsetWidth can return 0 if you've done certain DOM modifications to the element recently. You may have to call this code in a setTimeout call after you've modified the element.
Dan Fabulich
A: 

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.

questzen
I think he wants to center it vertically too, which is a right pain with CSS unless you can meet some specific criteria (e.g. known-size content)
Greg
A: 

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:

<style type="text/css">
    html,body {display:table; height:100%;width:100%;margin:0;padding:0;}
    body {display:table-cell; vertical-align:middle;}
    div {display:table; margin:0 auto; background:red;}
</style>
<body><div>test<br>test</div></body>

This is the perfect solution. It centers <div> of any size, and shrink-wraps it to size of its content.

porneL
A: 

also you can use this code: var divID = document.getElementById("divid");

var h = divID.style.pixelHeight;

A: 

The answer using "offsetWidth" is unfortunately wrong for most cases. I am struggling with this right now to find out the exact value. This offsetWidth returns a few pixels off (probably border, padding, who knows what). It's just a shame, this day and age, the exact size of an an element such as DIV is not easier retrieved.

nnull