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

Asked

Viewed 7,903 times

4

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

I realize that some cases the results are different.

2 answers

14


The difference is that the offset is related to the document, while the 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>

<div id="a">
  <div id="b"></div>
</div>

<p></p>


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

  • You mean the acenstrais they use position:relative?

  • 2

    Those who use position: qualquer-coisa-exceto-static.

  • It was nice to have asked this here then. I was with the totally wrong concept :|

2

This depends on the context the element is in. The position returns the position relative to the parent, and the offset does the same relative 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 displacement to the sub will be 200 : 200 , but its position will be 0 : 0.

Source: https://stackoverflow.com/questions/3202008/jquery-difference-between-position-and-offset

Browser other questions tagged

You are not signed in. Login or sign up in order to post.