It has probably happened to you at some point that you needed to implement new functionality that is based on getting the top position of an HTML element. After 10 seconds of searching on google (and probably ignoring the answers that contain jquery), here is the answer: element.offsetTop() . Everything is great, you copy-paste the function in your code and done, it returns the top position. You are lucky.

Well, now I’m gonna show you some little details of this property that you probably didn’t take into consideration.

Upon further investigation, from the MDN docs:

The HTMLElement.offsetTop read-only property returns the distance of the current element relative to the top of the offsetParent node.

So it seems that the offsetTop property does not actually take the “absolute” position but relative to its parent element that has a relative position.

Working example

A simple example of the offset property. If the element is a direct child of the body, it will work as expected.

Tricky example

the offset property takes values based on the nearest relative element

The solution

It is not very complicated, we need to iterate over all the parent elements that are references for positioning the element. The property to get all these elements is offsetParent .

Some other implementation example

offsetTop and offsetLeft have the same behavior

I hope I made these things a bit clearer.