Finding the size of an HTML Element
There are so many variables that affect the size of an element -- content length, CSS rules, font family, font size, line height, text zooming ... the list goes on. Add to this the fact that browsers interpret CSS dimensions and font sizes inconsistently, and you can never predict the dimensions at which an element will be rendered. The only consistent way to determine an element's size is to measure it once it's been rendered by the browser.
Solution
You can tell straight away that it's going to be useful to know exactly how big an element is. Well, the W3C can't help: there's no standardized way to determine the size of an element. Thankfully, the browser-makers have more or less settled on some DOM properties that let us figure it out.
Although box model differences mean that Internet Explorer includes padding and borders inconsistently as part of an element's CSS dimensions, the offsetWidth
and offsetHeight
properties will consistently return an element's width -- including padding and borders -- across all browsers.
Let's imagine that an element's dimensions were specified in CSS like this:
Example 13.15. find_size_element.css
#enterprise
{
width: 350px;
height: 150px;
margin: 25px;
border: 25px solid #000000;
padding: 25px;
}
We can determine that element's exact pixel width in JavaScript by checking the corresponding offsetWidth
and offsetHeight
properties:
Example 13.16. find_size_element.js (excerpt)
var starShip = document.getElementById("enterprise");
var pixelWidth = starShip.offsetWidth;
var pixelHeight = starShip.offsetHeight;
In Internet Explorer 6, Opera, Mozilla, and Safari, the variable pixelWidth
will now be set to 450, and the variable pixelHeight
will be set to 250. In Internet Explorer 5/5.5, pixelWidth
will be 350 and pixelHeight
150, because those are the dimensions at which the broken box model approach used in those browsers will render the element. The values are different across browsers, but only because the actual rendered size differs as well. The offset dimensions consistently calculate the exact pixel dimensions of the element.
If we did not specify the dimensions of the element, and instead left its display up to the default block rendering (thus avoiding the box model bugs), the values would be comparable between browsers (allowing for scrollbar width differences, fonts, etc.).
Can't find what you're looking for? Try Google Search!
Comments on "Finding the size of an HTML Element"