mauricevancooten / react-anchor-link-smooth-scroll

React component for anchor links using the smooth scroll polyfill.
243 stars 31 forks source link

Does not work when anchor is nested inside a parent with position: relative #19

Closed vai0 closed 5 years ago

vai0 commented 5 years ago

i.e.,

<AnchorLink href="#section-one">
  Take me to section one
</AnchorLink>
...
<div class="parent-with-relative-positioning">
  <div id="section-one">
    ...
  </div>
</div>

Clicking on the link produced by AnchorLink does not take me down to #section-one, but only moves me a distance #section-one relative to .parent-with-relative-positioning.

It looks to be due to how the distance is calculated with offsetTop, which gives the number of pixels from the top of the closest relatively positioned parent element.

Would a more ideal solution be something along these lines...

$elem.getBoundingClientRect().top + window.pageYOffset;

where the distance from the top of the page is calculated regardless of whether parents of sections are set to position: relative?