No scroll snap with scroll-snap-type and -align / Simple Example not working Chrome/Firefox /

2.9k Views Asked by At

Using Chrome / Firefox, I created a container (.container) for a couple of picture (list items with class img). I added scroll-snap-type on the container. I added scroll-snap-align on the items with class img.

What am I missing here?

HTML

<div class="container">
  <ul>
  <li class="img"><img src="https://picsum.photos/500"></li>
  <li class="img"><img src="https://picsum.photos/500"></li>
  <li class="img"><img src="https://picsum.photos/500"></li>
  <li class="img"><img src="https://picsum.photos/500"></li>
  <li class="img"><img src="https://picsum.photos/500"></li>
  <li class="img"><img src="https://picsum.photos/500"></li>
  </ul>
</div>

CSS

.img {
  margin: 10px 5px;
  scroll-snap-align: center;
  -webkit-overflow-scrolling: touch;
}

.container {
  display:  grid; 
  justify-content: center; 
  grid-gap: 10px;
  scroll-snap-type: y mandatory;
  overflow-y: scroll;
}
2

There are 2 best solutions below

2
On BEST ANSWER

As it turns out, scroll-snap-type requires that you define a height for the container. I am not exactly sure how to explain why it is required, however, defining a height does take care of the issue.

.img {
  margin: 10px 5px;
  scroll-snap-align: center;
  -webkit-overflow-scrolling: touch;
}

.container {
  display:  grid; 
  justify-content: center; 
  grid-gap: 10px;
  scroll-snap-type: y mandatory;
  overflow-y: scroll;
  height: 100vh;
}
0
On

After many tries and exploration (this is 2023) I wanted to leave what worked for me. Sooo, if anyone needs help, this is what worked for me.

  1. Don't use scroll-snap-type: y mandatory
  2. Create element and use scroll-snap-type: y mandatory on it
  3. In order for scroll-snap-type: y mandatory to work you have to add height to that element and also overflow: scroll
  4. On the children elements (that actually need to snap) you have to add scroll-snap-align: start;
  5. They do not have to have height specified (at least in my case) but I still put it 100vh so everything is nice an equal.

Here is a HTML example:

<html>
    <body>
      <div id="container">
          <div class="child"></div>
          <div class="child"></div>
          <div class="child"></div>
      </div>
    </body>
</html>

Here is CSS code:

#container {
    overflow: scroll;
    scroll-snap-type: y mandatory;
    height: 100vh;
}
.child {
    scroll-snap-align: start;
    height: 100vh;
}

Everything is working good now.