The code is like this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
html {
border: 1px solid black;
padding: 0;
}
body {
width: 100px;
height: 100px;
border: 10px solid red;
padding: 10px;
margin: 10px;
}
div {
width: 100px;
height: 100px;
border: 10px solid black;
padding: 10px;
margin: 10px;
}
</style>
</head>
<body>
<div id="div"></div>
</body>
</html>
Why the offsetLeft value of the div element is offsetLeft is 41?
It should be div.leftMargin + body.leftPadding = 20px.
Is this a chrome bug or did I misunderstand offsetLeft?
It does seem as though Chrome and Firefox have interpreted things differently.
From MDN:
The HTMLElement.offsetParent read-only property returns a reference to the element which is the closest (nearest in the containment hierarchy) positioned ancestor element. If there is no positioned ancestor element, the nearest ancestor td, th, table will be returned, or the body if there are no ancestor table elements either.
However, it seems that Chrome is not using body as the closest ancestor in this case but is going back to the html element. If you give the body element a position: relative then Chrome gives a leftOffset of 30.
Here's a snippet to play with - try different box-sizing and different positioning, or not, of body.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
* {
box-sizing: border-box;
}
html {
border: 1px solid black;
padding: 0;
}
body {
width: 100px;
height: 100px;
border: 10px solid red;
padding: 10px;
margin: 10px;
}
#div {
width: 100px;
height: 100px;
border: 10px solid black;
padding: 10px;
margin: 10px;
}
</style>
</head>
<body style="position: relative;">
<div id="div"></div>
<script>
alert(document.querySelector('#div').offsetLeft);
</script>
</body>
</html>
So, I realise this is more an extended comment/observations than a full answer but too long for a comment. Someone else can hopefully fully explain and/or find a reference to a potential Chrome bug/different interpretation.