I have a webpage on which I would like to scroll to a certain element.
That part works fine by using scrollIntoView
; but I would like to add a bit of space
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);
};