JavaScript Positioning

January 20, 2006

To find out exactly how browsers were interpreting offsetLeft and offsetTop, I built a test page that would tell me I added a 1px margin, 2px border, 4px padding, 8px position, 16px margin, and so on and then used bitwise AND to figure out which parts were being included in the total calculation. what parts of the style calculation were included.

It’s a mess. Firefox and Opera do the calculation in the same way, while Safari and IE each have unique interpretations. IE has the only obvious bug, where the top padding of an element is not included in one calculation, while the left padding is.

The only thing that appears to work consistently is finding an element’s absolute position on a page—as long as no elements have any borders, margins, or padding.

It is possible to get the browsers a little closer to the correct answer if you include the IE-specific clientTop and clientLeft properties. Here’s a test page to demonstrates this. In this case, Safari, IE, and Opera agree on the absolute x coordinate, IE still won’t include y padding, and Firefox is on its own.

I think this comment sums up the problem nicely:

“The problem to begin with, the origin of the problem is that MSDN does not define strictly, explicitly how offsetLeft/offsetTop should be computed in normal situations and in various other situations. Even offsetParent is not defined clearly: there is no precise spec. - formal rigorous spec - identifying how the offsetParent can be, should be determined. offsetLeft, offsetTop definitions are circularly dependent, self-inter-dependent to offsetParent definition.

Add to this quirks mode vs standards rendering mode, and other properties (padding, border, margin, box-sizing) which interfere or affect too calculations of offsetLeft, offsetTop or which may influence too the way offsetParent is to be defined and then you have a real mess, headache, impossible task.”

Archives