Berl
Berl

Reputation: 65

How to get CSS scroll snap to work properly?

I don't get the scroll snap to work in my project. Can you find the bug? I watched many videos and read blog posts about scroll snap in CSS but everything I see is what I've already tried. I just get a normal scroll behaviour.

* {
  margin: 0;
  padding: 0;
}

.scrollcontainer {
  scroll-snap-type: y mandatory;
  scroll-snap-points-y: repeat(100vh);
}

.scrollchild {
  scroll-snap-align: start;
  background-color: #000000;
  height: 100vh;
}

.scrollchild:nth-of-type(even) {
  background: #ffffff;
}
<div class="scrollcontainer">
  <section class="scrollchild">
    <p>one</p>
  </section>
  <section class="scrollchild">
    <p>two</p>
  </section>
</div>

Upvotes: 3

Views: 163

Answers (1)

alotropico
alotropico

Reputation: 1994

Your only problem is that the scroll is not in the scrollcontainer but in the body. scrollcontainer never actually scrolls.

This should fix that:

* {
    margin: 0;
    padding: 0;
}

.scrollcontainer {
    scroll-snap-type: y mandatory;
    scroll-snap-points-y: repeat(100vh);
    
    height: 100vh;
    overflow-y: scroll;
}

.scrollchild {
    scroll-snap-align: start;
    background-color: #000000;
    height: 100vh;
}

.scrollchild:nth-of-type(even) {
    background: #ffffff;
}
<div class="scrollcontainer">
<section class="scrollchild">
  <p>one</p>
</section>
<section class="scrollchild">
  <p>two</p>
</section>
</div>

Upvotes: 2

Related Questions