'Why does offsetLeft of the body not include the margin?
I’m trying to get the offsetLeft value of several elements. I get the expected value for every element except for the body element.
The offsetLeft value for each child element includes its own margin-left value plus the margin-left value for each ancestor element including the body as expected. However offsetLeft for the body element does not include its own margin-left value of 2px and returns 0.
Why does offsetLeft of the body not include the margin?
Developer tools shows the body element has a margin of 2px for all 4 sides.
Note I see a different issue for margin-top but I assume that is because of margin collapsing.
I get the same results in both Chrome and Firefox.
Here are the results from the code.
body offset left: 0 top: 0 width: 400 height: 400 margin-left: 2px
div1 offset left: 7 top: 5 width: 390 height: 18 margin-left: 5px
div2 offset left: 12 top: 5 width: 380 height: 18 margin-left: 5px
Below is the complete code sample.
<!DOCTYPE html>
<head>
<style>
* {
box-sizing: border-box;
}
body {
margin: 2px;
width: 400px;
height: 400px;
}
#div1 {
margin: 5px;
}
#div2 {
margin: 5px;
}
</style>
</head>
<body id="body" >
<div id="div1">
<div id="div2">Div 2</div>
</div>
</body>
<script>
let body = document.getElementById('body');
let div1 = document.getElementById('div1');
let div2 = document.getElementById('div2');
let marginLeftBody = window.getComputedStyle(body).getPropertyValue('margin-left');
let marginLeftDiv1 = window.getComputedStyle(div1).getPropertyValue('margin-left');
let marginLeftDiv2 = window.getComputedStyle(div2).getPropertyValue('margin-left');
console.log(`body offset left: ${body.offsetLeft} top: ${body.offsetTop} width: ${body.offsetWidth} height: ${body.offsetHeight} margin-left: ${marginLeftBody}`);
console.log(`div1 offset left: ${div1.offsetLeft} top: ${div1.offsetTop} width: ${div1.offsetWidth} height: ${div1.offsetHeight} margin-left: ${marginLeftDiv1}`);
console.log(`div2 offset left: ${div2.offsetLeft} top: ${div2.offsetTop} width: ${div2.offsetWidth} height: ${div2.offsetHeight} margin-left: ${marginLeftDiv2}`);
</script>
</html>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
