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).
Jquery dimensions plugin.
var height = $("#myDiv").height();
var width = $("#myDiv").width();
var docHeight = $(document).height();
var docWidth = $(document).width();
You should use the .offsetWidth
and .offsetHeight
properties.
Note they belong to the element, not .style
.
var width = document.getElementById('foo').offsetWidth;
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.
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.
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.