How do I get the position of a Div relatively to its parent Div? Using .position() and .offset() always gives me its position to the document.
HTML:
<div id="frame">
<div id="inner"></div>
</div>
CSS:
Let’s assume frame is centered with margin: auto; and width: 1024px.
inner has left: 300px;, top: 200px and position: relative;.
What I want:
A nice function for getting inners‘s position data 300 and 200 (e.g. without px when using .css('left') etc.
Is there anything?
If you give the parent a “position” of “relative”, then using
.position()should be its position inside of the parent.Using
.offsetactually should always give you its position based off thedocument, while using.positiongives you its “position” based off its first parent whose “position” is not “static” (default).Here’s examples:
http://jsfiddle.net/Z2VNx/
http://jsfiddle.net/Z2VNx/1/
The first example uses
<br />to add space at the top of the container, while the second example usespadding-topto add space at the top of the container. Both return a value greater than0for the child’stopposition.The only problem is that
positiondoes not account for the child’s margins, padding, and borders when calculating its position. This is because all of those are part of the element, so even though you may not visually see them, they wouldn’t be included in the element’s position calculation. So of course, depending on exactly what part of the element you want to see its position of, you need to add that to the result of.position. Some people want the “position” to return to top-left position of the border, which would mean adding the margin. Something like this:http://jsfiddle.net/Z2VNx/2/