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);
};
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
In general it's not very straightforward (if we want behavior: smooth
), and will require messing with javascript in one way or another. For example you could use window.scrollTo and calculate necessary top position manually.
In some cases however you could visually achieve necessary effect by using CSS smartly. In your demo you can use padding-top
instead of margin and wrap content of the block into additional helper container.
Demo: https://codepen.io/anon/pen/OvKQLV
Another potential solution is to scroll not the the element itself, but to one of its previous siblings. Example:
let elementToScrollTo = <yourTargetElement>;
const childOffset = 3;
for (let i = 0; i < childOffset; i++) {
if (!elementToScrollTo.previousElementSibling) {
break;
}
elementToScrollTo = elementToScrollTo.previousElementSibling;
}
elementToScrollTo.scrollIntoView();
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;
}