CSS滚动-捕捉到位



我正试图使用CSS为网站实现垂直对齐滚动,但很难实现。为了隔离这个问题,我创建了这个玩具示例:

#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>

然而,一切仍然自由滚动。我哪里错了?谢谢

在我看到的MDN中使用滚动捕捉的所有示例中,父元素始终具有定义的高度,并且对于您使用的方向有溢出,在您的情况下为y=>CCD_ 2。如果没有定义的高度,在我的测试中,捕捉将不起作用。

现在,由于body具有默认滚动,因此必须在css中为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>

最新更新