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 above the element (20px
or something)
I'm currently doing something like this:
const moveToBlue = () => { const blue = document.getElementById('blue') blue.scrollIntoView({ behavior: 'smooth', block: 'start', inline: 'start'}); };
I would however like to scroll futher 20px up (see my demo here)
Is this possible?
Native method: scrollIntoView The usage is simple, just like this: function scroll(e) {e. scrollIntoView({behavior: "smooth", block: "start"});}scroll(document. getElementById(YOUR_DIV_ID));
The scroll-margin-top property is used to set all the scroll margins to the top of an element at once. The value specified for the scroll-margin-top determines how much of the page that is primarily outside the support should remain visible.
The scrollIntoView() method scrolls an element into the visible area of the browser window.
Use the ::-webkit-scrollbar selector, give the bar a fixed with of x pixels. then set the left property to some -px value.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With