mykiwi
mykiwi

Reputation: 1693

scroll-snap-align and scroll-snap-type not enough?

I'm trying to use this :
https://developer.mozilla.org/docs/Web/CSS/scroll-snap-type
https://developer.mozilla.org/docs/Web/CSS/scroll-snap-align

Example I want to reproduce: https://codepen.io/mykiwi/pen/xxwPKJr?editors=1100

<div class="scroller">
    <div>1</div>
    <div>2</div>
    <div>3</div>
    <div>4</div>
    <div>5</div>
    <div>6</div>
</div>
.scroller {
  text-align:left;
  height:250px;
  width:270px;
  overflow-y:scroll;
  display:flex;
  flex-direction:column;
  box-sizing:border-box;
  border:1px solid #000;
  scroll-snap-type:y mandatory
}
.scroller>div {
  flex:0 0 250px;
  background-color:#663399;
  color:#fff;
  font-size:30px;
  display:flex;
  align-items:center;
  justify-content:center;
  scroll-snap-align:start;
}
.scroller>div:nth-child(even) {
  background-color:#fff;
  color:#663399
}

My code: https://codepen.io/mykiwi/pen/mdeqePo?editors=1100
I have Bulma in background too

What is wrong/missing from my CSS to reproduce the example ?
Thanks

Upvotes: 1

Views: 821

Answers (1)

SMAKSS
SMAKSS

Reputation: 10520

This is a bit tricky to get it working and since the MDN does not describe it very well, this makes it harder.


What is the problem exactly?

The wrapping element you provided does not meet the expectation for doing such an action. So what does it mean?

To ensure the scroll-snap-type is working correctly we should make sure the only available scrollbar in our window is our wrapping element scrollbar, which is in your case it is a division by class name screen.

How to fix it?

So all you have to do is to make sure the scroll element is exactly related to your parent wrapping element which in your case its indicated by screen class name. To make sure the scrollbar you seeing in the right one you should make the body and html, overflow to hidden to prevent them from scrolling. just like this:

html,
body {
  overflow: hidden;
}

Then you need to enable the right scrollbar, which belongs to the screen division.

.screen {
  height: 100vh;
  overflow-y: scroll;
  scroll-snap-type: y mandatory;
}

So it will work like a charm.

Here is the live working example: codepen.io


Also, there is a similar issue in SO, that you can find here.

Upvotes: 5

Related Questions