The HTML DOM offsetLeft property returns a number corresponding to the left position of the specified element relative to the left side of the parent element.
Following is the syntax −
Returning number value in pixels (px)
HTMLelement.offsetLeft
Here, returned value corresponds to −
- The left position and margin of the specified element
- The left padding, scrollbar, border, and margin of the parent element
Let us see an example of HTML DOM offsetLeft property −
Example
<!DOCTYPE html>
<html>
<head>
<title>HTML DOM offsetLeft</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-offsetLeft</legend>
<div id="containerDiv">
<img id="image" src="https://www.tutorialspoint.com/ios/images/ios-mini-logo.jpg">
</div>
<input type="button" onclick="getLeft()" value="Get offsetLeft">
<div id="divDisplay"></div>
</fieldset>
</form>
<script>
var divDisplay = document.getElementById("divDisplay");
var picForm = document.getElementById("picForm");
var containerDiv = document.getElementById("containerDiv");
function getLeft() {
// window.getComputedStyle() gets the computed css
var style = window.getComputedStyle(picForm);
var style2 = window.getComputedStyle(document.body);
divDisplay.innerHTML = 'Left Offset of form: '+picForm.offsetLeft+'px';
divDisplay.innerHTML += '<br>Left position of Child(form): '+style.left;
divDisplay.innerHTML += '<br>Left margin of Child(form): '+style.marginLeft;
divDisplay.innerHTML += '<br>Left padding of Parent(body): '+style2.paddingLeft;
divDisplay.innerHTML += '<br>Left border of Parent(body): '+style2.borderLeftWidth;
divDisplay.innerHTML += '<br>Left margin of Parent(body): '+style2.marginLeft;
}
</script>
</body>
</html>Output
Before clicking any button −

After clicking ‘Get offsetLeft’ button −
