HTML DOM Element offsetTop attribute

Definition and Usage

offsetTop This property returns the top position relative to the parent (in pixels). This property is read-only.

The returned value includes:

  • Element's top position and margin
  • Parent's top inner padding, scrollbars, and borders

See also:CSS Box Model Tutorial

offsetParent

All block-level elements report offsets relative to the offset parent:

  • offsetTop
  • offsetLeft
  • offsetWidth
  • offsetHeight

Offset parent refers to the nearest ancestor with a non-static position.

If there is no offset parent, the offset is relative to the main body of the document.

See also:

offsetLeft attribute

offsetWidth attribute

offsetHeight attribute

offsetParent property

clientTop property

clientLeft property

clientWidth property

clientHeight property

Example

Example 1

Get the offsetTop position of "myDIV":

const element = document.getElementById("myDIV");
let pos = element.offsetTop;

Try It Yourself

Example 2

Get the position of "myDIV":

const element = document.getElementById("test");
Let pos1 = element.offsetTop;
let pos2 = element.offsetLeft;

Try It Yourself

Example 3

Create a Sticky Navigation Bar:

// Get the navigation bar
const navbar = document.getElementById("navbar");
// Get the offset position of the navigation bar
const sticky = navbar.offsetTop;
// Add the sticky class to the navigation bar when you reach its scroll position. Remove the sticky class when you leave the scroll position.
function myFunction() {
  if (window.pageYOffset >= sticky) {
    navbar.classList.add("sticky")
  }
    navbar.classList.remove("sticky");
  }
}

Try It Yourself

Syntax

Returns the top offset position:

element.offsetTop

Return Value

Type Description
Number The top position of the element, measured in pixels.

Browser Support

All browsers support element.offsetTop:

Chrome IE Edge Firefox Safari Opera
Chrome IE Edge Firefox Safari Opera
Support Support Support Support Support Support