scrollIntoView with margin

后端 未结 5 1516
孤独总比滥情好
孤独总比滥情好 2021-02-19 08:14

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

相关标签:
5条回答
  • 2021-02-19 08:42

    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);
    };
    
    0 讨论(0)
  • 2021-02-19 08:45

    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

    0 讨论(0)
  • 2021-02-19 08:53

    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

    0 讨论(0)
  • 2021-02-19 08:55

    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();
    
    0 讨论(0)
  • 2021-02-19 09:01

    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;
    }
    
    0 讨论(0)
提交回复
热议问题