Wednesday, March 29, 2006

Differences between Element.offsetWidth and CSS width property

I'm sure most CSS jockeys are probably already aware of this, but I'll make a note of it for posterity.

This information is specifically for IE6 in Strict mode. Other browsers differ in their implementation of the box model.

The width property in CSS and the offsetWidth property in JavaScript are two very different things. For example, if you set an element's width to 500px in CSS, the element's offsetWidth may not be 500, depending on the margins, borders, and padding you have applied to the element. Here's how it breaks down:

Element.offsetWidth = CSS width + total horizontal padding width + total horizontal border width

Example:

width:300px, border:5px solid green, padding:5px, margin:5px


In IE6 strict mode, the offsetWidth will return 320, rather than 300 as you might expect. Also, offsetWidth does not include the margin, so to get the actual width that the element takes up on the screen, you have to add the total horizontal margin to the offsetWidth.

Was this post helpful to you? If so, please consider making a small donation to keep this blog going.

2 Comments:

Anonymous Anonymous said...

I notice in FF 1.5x the total box width is also 320px. Is that the anticpated results for the box width in FF?

8:10 AM  
Blogger tom said...

That's correct. At the time I wrote this, I put in the IE-only disclaimer because I didn't have time to actually test it across different browsers. However, the results should be the same across all standards-compliant browsers.

8:33 AM  

Post a Comment

<< Home