The HTML DOM offsetTop property returns a number corresponding to the top position of the specified element relative to the top side of the parent element.
Following is the syntax −
Returning number value in pixels (px)
HTMLelement.offsetTop
Here, returned value corresponds to −
- The top position and margin of the specified element
- The top padding, scrollbar, border, and margin of the parent element
Let us see an example of HTML DOM offsetTop property −
Example
<!DOCTYPE html> <html> <head> <title>HTML DOM offsetTop</title> <style type="text/css"> #picForm { width:70%; margin: 0 auto; text-align: center; } input[type="button"] { border-radius: 10px; } #containerDiv { margin: 0 auto; } </style> </head> <body> <form id="picForm"> <fieldset> <legend>HTML-DOM-offsetTop</legend> <div id="containerDiv"> <img id="image" src="https://www.tutorialspoint.com/compiler_design/images/compiler-design-mini-logo.jpg"> </div> <input type="button" onclick="getHeight()" value="Get offsetTop"> <div id="divDisplay"></div> </fieldset> </form> <script> var divDisplay = document.getElementById("divDisplay"); var picForm = document.getElementById("picForm"); var containerDiv = document.getElementById("containerDiv"); function getHeight() { // window.getComputedStyle() gets the computed css var style = window.getComputedStyle(picForm); var style2 = window.getComputedStyle(document.body); divDisplay.innerHTML = 'Top Offset of form: '+picForm.offsetTop+'px'; divDisplay.innerHTML += '<br>Top position of Child(form): '+style.Top; divDisplay.innerHTML += '<br>Top margin of Child(form): '+style.marginTop; divDisplay.innerHTML += '<br>Top padding of Parent(body): '+style2.paddingTop; divDisplay.innerHTML += '<br>Top border of Parent(body): '+style2.borderTopWidth; divDisplay.innerHTML += '<br>Top margin of Parent(body): '+style2.marginTop; } </script> </body> </html>
Output
Before clicking any button −
After clicking ‘Get offsetTop’ button −