htmlcssvertical-scrollingscroll-snap

CSS Scrolling - snap into place?


I'm trying to implement vertical snap-into-place scrolling using CSS for a site, but having trouble getting it to work. To isolate the problem, I created this toy example:

#container {
  scroll-snap-type: y mandatory;
}

.tile {
  height: 100vh;
  width: 100vw;
  scroll-snap-align: start;
}
<div id="container">
  <div class="tile" style="background-color:red;">
  </div>
  <div class="tile" style="background-color:blue;">
  </div>
  <div class="tile" style="background-color:green;">
  </div>
  <div class="tile" style="background-color:yellow;">
  </div>
</div>

However everything still scrolls freely. Where am I going wrong? Thanks!


Solution

  • On all examples at MDN I have seen using scroll snapping the parent element always has a defined height and an overflow for the direction you are using, in your case y => overflow-y: scroll;. Without the defined height, in my testing the snapping will not work.

    Now, since the body has the default scrolling the height must be defined in the css for body.

    html,
    body {
      height: 100vh;
      overflow: hidden;
    }
    
    #container {
      overflow: scroll;
      height: 100vh;
      scroll-snap-type: y mandatory;
    }
    
    #container div {
      height: 100vh;
      scroll-snap-align: start;
    }
    <div id="container" style="">
      <div class="tile" style="background-color:red;">
      </div>
      <div class="tile" style="background-color:blue;">
      </div>
      <div class="tile" style="background-color:green;">
      </div>
      <div class="tile" style="background-color:yellow;">
      </div>
    </div>