jQuery offset().top returns wrong value - error with margin jQuery offset().top returns wrong value - error with margin javascript javascript

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.