HTML DOM Element offsetTop

Example

Get the offsetTop position of "myDIV":

const element = document.getElementById("myDIV");
let pos = element.offsetTop;
Try it Yourself »

Get the positions of "myDIV":

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

More examples below.


Description

The offsetTop property returns the top position (in pixels) relative to the parent.

The returned value includes:

  • the top position, and margin of the element
  • the top padding, scrollbar and border of the parent

The offsetTop property is read-only.

Tutorial:

CSS Box Model

The offsetParent

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

  • offsetTop
  • offsetLeft
  • offsetWidth
  • offsetHeight

The offset parent is the nearest ancestor that has a position other than static.

If no offset parent exists, the offset is relative to the document body.

See Also:

The offsetLeft Property.

The offsetWidth Property.

The offsetHeight Property.

The offsetParent Property.

The clientTop Property

The clientLeft Property

The clientWidth Property

The clientHeight Property



Syntax

Return the top offset position:

element.offsetTop

Return Value

Type Description
NumberThe top position of the element, in pixels.

More Examples

Create a sticky navigation bar:

// Get the navbar
const navbar = document.getElementById("navbar");

// Get the offset position of the navbar
const sticky = navbar.offsetTop;

// Add the sticky class to the navbar 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")
  } else {
    navbar.classList.remove("sticky");
  }
}
Try it Yourself »

Browser Support

element.offsetTop is supported in all browsers:

Chrome Edge Firefox Safari Opera IE
Yes Yes Yes Yes Yes Yes

Copyright 1999-2023 by Refsnes Data. All Rights Reserved.