Search code examples
htmlcssscroll-snap-points

What are the bare necessities for CSS snap scroll to work?


I've been trying to implement a super simple horizontal snap scroll (as shown here: https://css-tricks.com/practical-css-scroll-snapping ) yet I am consistently failing at that. I've probably searched through all the questions and answers here but none was of help.

My code is very simple, I am only declaring scroll-snap-type: y mandatory; on the parent and scroll-snap-align: center; on the child. And I am pretty sure it's not a browser issue (since I've tried it with many different browsers). What am I missing here? Or what do I not understand?

Here's my (not working) CodePen: https://codepen.io/anon/pen/XyNNGY

html:

<div class='parent'>
  <div class='child'>Section 1</div>
  <div class='child two'>Section 2</div>
  <div class='child'>Section 3</div>
</div>

css:

  body {
    margin: 0;
  }

  .parent {
    scroll-snap-type: y mandatory;
  }

  .child {
    scroll-snap-align: center;
    width: 100vw;
    height: 100vh;
    background-color: pink;
  }

  .two {
    background-color: crimson;
  }

Thanks a million already.


Solution

  • The element you designate as the scroll snap container needs to be the one that the scrollbar is attached to. In your case, the parent element doesn't have a scrollbar — the scrollbar belongs to the viewport and the parent is extending past the size of the viewport without generating its own scrollbar. The scroll-snap-type property should therefore be applied to body (or html), not the parent:

    body {
      margin: 0;
      scroll-snap-type: y mandatory;
    }
    
    .child {
      scroll-snap-align: center;
      width: 100vw;
      height: 100vh;
      background-color: pink;
    }
    
    .two {
      background-color: crimson;
    }
    <div class='parent'>
      <div class='child'>Section 1</div>
      <div class='child two'>Section 2</div>
      <div class='child'>Section 3</div>
    </div>