0

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;
}
basti
  • 123
  • 1
  • 10

2 Answers2

6

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;
}
Talha Azhar
  • 223
  • 2
  • 6
  • Thanks. I'd read everything and couldn't get it to work correctly until I found your code. – TenLeftFingers Feb 12 '21 at 12:16
  • I think the requirement of defining a height serves to prevent the container from simply accommodating its contents by stretching vertically. If the container is high enough to contain all its children, no need for scrolling. No scrolling, no snapping. – Shawn Feb 06 '22 at 01:38
  • This answer solved my problem. – Korovjov Sep 01 '23 at 17:34
0

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.

Korovjov
  • 503
  • 5
  • 17