Reputation: 7547
I was reading about the jQuery.position() document here, the example code prints position.left
= 15 while when I tested the same code at codepen here (both on chrome and firefox) it prints 23. It seems that the <body>
has 8px margins, and it adds to the 15px padding in the <div>
, and it results 23px. But as the official document says, this function "retrieve the current position of an element relative to the offset parent", then why those major browser output 23 instead of 18?
example code:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>position demo</title>
<style>
div {
padding: 15px;
}
p {
margin-left: 10px;
}
</style>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<div>
<p>Hello</p>
</div>
<p></p>
<script>
var p = $( "p:first" );
var position = p.position();
$( "p:last" ).text( "left: " + position.left + ", top: " + position.top );
</script>
</body>
</html>
Upvotes: 0
Views: 52
Reputation: 414
Like when playing around with "position: absolute" items and trying to position them, the offset parent is not the direct parent. It walks up the dom until it finds parent which is not in default layout-mode. Using any non-static position on the parent will set this as offset-container for your element.
In your example there weren't any offset parents in non-static mode so it took the body as parent.
As Yogesh Sharma suggested: setting the following should help:
div {position:relative;}
Upvotes: 2