Reputation: 3990
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?
Upvotes: 0
Views: 291
Reputation: 50905
If you give the parent a "position" of "relative", then using .position()
should be its position inside of the parent.
Using .offset
actually should always give you its position based off the document
, while using .position
gives you its "position" based off its first parent whose "position" is not "static" (default).
Here's examples:
The first example uses <br />
to add space at the top of the container, while the second example uses padding-top
to add space at the top of the container. Both return a value greater than 0
for the child's top
position.
The only problem is that position
does 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:
Upvotes: 4