2

Consider the following diagram:

enter image description here

I would like to calculate the vertical offset of the child element within its immediate parent. Note that the child element has a margin (indicated by the lighter blue).

jQuery provides .position(), but unfortunately the method calculates offset:

"...relative to the offset parent."

The parent element in this case does not have position set to relative and unfortunately this cannot be changed.

In spite of this, is there any way to get the child element's offset relative to its immediate parent?

1 Answer 1

2

You can do that with

$(this).offset().top - $(this).parent().offset().top
3
  • 1
    I don't think that takes the parent's border into account, does it? If the parent element has an 8px border, for example, the calculation above will result in an offset that is 8px larger than it should be. Nov 8, 2013 at 23:26
  • @NathanOsman: Unfortunately it does not. Assuming that the border is uniform you can compensate by subtracting $parent.outerHeight() - $parent.height(), but this does nothing for margins on the parent.
    – Jon
    Nov 8, 2013 at 23:38
  • @NathanOsman Are you able to change the CSS of the parent or child? If you can, you could add box-sizing: border-box; and not have to worry about the border. Nov 9, 2013 at 0:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.