anxpara
KPCKevin Powell - Community
•Created by anxpara on 12/17/2022 in #front-end
offsetTop not always correct when offsetParent is body
So according to the specs, offsetTop is "the distance between the outer border of the current element relative to the inner border of the top of the offsetParent."
And the offsetParent is "the element which is the closest (nearest in the containment hierarchy) positioned ancestor element," but "if there is no positioned ancestor element, the body is returned."
However, I've noticed that in the 3 major browsers / rendering engines, if an element's offsetParent is body, and body is static, then the following properties are ignored: body margin and border, and <html> margin, border, or padding. That means that the element's offset top and left are actually relative to the viewport, not the body.
So if an element's offsetParent is body and its offsetTop/Left are (0, 0) then the element is rendered at the viewport's (0, 0), not the body's inner border (0, 0).
Is this a bug? This seems to contradict the specs.
If I want the true offsetTop and offsetLeft then I'm forced to calculate it myself by adding all of the body/<html> margins and borders. However, if the body itself is positioned, then rendering engines do render the elements within the body's inner border.
It really seems like the meaning of offsetParent is muddied by all this.
6 replies
KPCKevin Powell - Community
•Created by anxpara on 12/6/2022 in #front-end
offsetTop and offsetHeight but with subpixel precision?
19 replies