jQuery offset().top returns wrong value - error with margin
Your question:
What is the solution for this problem?
I suggest you to position the .container
to relative
:
.container{ margin-top:100px; background:yellow; height:600px; width:300px; overflow-y:auto; overflow-x:hidden; position:relative; /*<---add this*/}
and within your script use .position().top
, it will make your life easier:
$('.container li:nth-child(7)').css("background", "red");$('.container').animate({ scrollTop: $('.container li:nth-child(7)').position().top});
.offset().top
:
Description: Get the current coordinates of the first element in the set of matched elements, relative to the document..
.position().top
:
From the docs:
Description: Get the current coordinates of the first element in the set of matched elements, relative to the offset parent.
.position().top
is calculated from the top to the parent if parent is relatively positioned.
You can also encounter this problem if some of your content is images. If you're calling .offset() inside document.ready(), the images may not have loaded yet. Try moving your .offset() call to window.load().
I had the same problem. All solutions in the web don't work for me.
If you use margin to seperate certain elements without borders, use padding instead. jQuery's offset() will count for paddings but excludes margins. The position numbers in offset() will become correct again.