kodeaben
kodeaben

Reputation: 2055

scrollIntoView with margin

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?

Upvotes: 78

Views: 66099

Answers (5)

colinux
colinux

Reputation: 4579

You can set scroll-margin CSS property on the scroll target element. For example

.blue {
  scroll-margin: 20px;
}

(or more specifically scroll-margin-top or scroll-margin-bottom)

https://developer.mozilla.org/en-US/docs/Web/CSS/scroll-margin

Upvotes: 227

Mohsin Mahmood
Mohsin Mahmood

Reputation: 3436

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

Upvotes: 7

wizzfizz94
wizzfizz94

Reputation: 1556

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

Upvotes: 10

Daniel Veihelmann
Daniel Veihelmann

Reputation: 1477

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

Upvotes: 3

dfsq
dfsq

Reputation: 193261

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

Upvotes: 3

Related Questions