scrollIntoView with margin

You can set scroll-margin CSS attribute on the scroll target element. For example

.blue {
  scroll-margin: 20px;
}

https://developer.mozilla.org/en-US/docs/Web/CSS/scroll-margin


That helped in my case —
HTML

<div class='stick-to-top'></>

Javascript

document.getElementsByClassName('stick-to-top')[0].scrollIntoView({behavior: "smooth", block: "center"});

CSS

.stick-to-top {
 padding-bottom: 400px;
}

You can always use scrollTo by first getting the elements coordinates using getBoundingClientRect then adding the scroll offset and taking your scroll margin. e.g.

const moveToBlue = () => {
  const blue = document.getElementById('blue');
  let position = blue.getBoundingClientRect();
  // scrolls to 20px above element
  window.scrollTo(position.left, position.top + window.scrollY - 20);
};