What is the difference between offset (). top and position (). top in jQuery?

3

What is the difference between $(el)offset().top and $(el).position().top in jQuery?

I notice that in some cases the results are different.

    
asked by anonymous 16.10.2015 / 18:02

2 answers

10

The difference is that offset is relative to the document, whereas position is relative to the nearest positioned ancestor (*).

For example:

var b = $('#b');
var offsetTop = b.offset().top;
var posTop = b.position().top;

$('p').text('O div de dentro está a ' + offsetTop + 'px do topo do documento, e a ' + posTop + 'px do div de fora')
div {      
    position: relative;
    top: 20px;
    left: 20px;
    min-height: 50px;
    padding: 20px;
    border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divid="a">
  <div id="b"></div>
</div>

<p></p>

(*) An ancestor positioned is any element above in the DOM tree which has position: qualquer-coisa-exceto-static .

    
16.10.2015 / 18:04
2

This depends on the context that the element is in. The position returns the position relative to the parent, and the offset does the same with respect to the document. Obviously, if the document is the offset parent, which is usually the case, these will be identical.

If you have a layout like this, however:

<div style="position: absolute; top: 200; left: 200;">
     <div id="sub"></div>
 </div>

Then the offset to the sub will be 200: 200, but its position will be 0: 0.

Source: link

    
16.10.2015 / 18:09