let's say I have the follwing function:
window.smoothScroll = function(target) {
var scrollContainer = target;
scrollContainer.scrollIntoView(true);
}
How can I make the page scroll 20px above the element instead of scrolling to the element itself?
Thank you
Edit due to CSS getting updated
Use scroll-margin-top
, introduced after the original answer was written.
Original 2018 answer
Get the dimensional information for your element and then rather than scrolling it into view, tell the window to scroll to your element's top
minus 20:
function scrollToJustAbove(element, margin=20) {
let dims = element.getBoundingClientRect();
window.scrollTo(window.scrollX, dims.top - margin);
}