Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scrollIntoView with margin

Tags:

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?

like image 225
methgaard Avatar asked Apr 16 '18 13:04

methgaard


People also ask

How do I make my scrollIntoView smooth?

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));

What is scroll margin top?

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.

What is scrollIntoView?

The scrollIntoView() method scrolls an element into the visible area of the browser window.

How do you put a scrollbar margin in CSS?

Use the ::-webkit-scrollbar selector, give the bar a fixed with of x pixels. then set the left property to some -px value.


1 Answers

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

like image 102
colinux Avatar answered Oct 03 '22 22:10

colinux