scrollIntoView Scrolls just too far

Smooth scroll to the proper position (Outdated)

There is the better answer which uses scroll-margin and scroll-padding css rules. getBoundingClientRect in this solution triggers additional forced layout and may cause unnecessary performance issues.

Get correct y coordinate and use window.scrollTo({top: y, behavior: 'smooth'})

const id = 'profilePhoto';
const yOffset = -10; 
const element = document.getElementById(id);
const y = element.getBoundingClientRect().top + window.pageYOffset + yOffset;

window.scrollTo({top: y, behavior: 'smooth'});

Leave a Comment