水平滚动捕捉
创建一个水平滚动的容器,在滚动时会捕捉到元素。
- 使用
display: grid
和grid-auto-flow: column
创建水平布局。 - 使用
scroll-snap-type: x mandatory
和overscroll-behavior-x: contain
创建水平滚动的捕捉效果。 - 将
scroll-snap-align
更改为start
、stop
或center
来更改捕捉对齐方式。
<div class="horizontal-snap">
<a href="#"><img src="https://picsum.photos/id/1067/640/640"></a>
<a href="#"><img src="https://picsum.photos/id/122/640/640"></a>
<a href="#"><img src="https://picsum.photos/id/188/640/640"></a>
<a href="#"><img src="https://picsum.photos/id/249/640/640"></a>
<a href="#"><img src="https://picsum.photos/id/257/640/640"></a>
<a href="#"><img src="https://picsum.photos/id/259/640/640"></a>
<a href="#"><img src="https://picsum.photos/id/283/640/640"></a>
<a href="#"><img src="https://picsum.photos/id/288/640/640"></a>
<a href="#"><img src="https://picsum.photos/id/299/640/640"></a>
</div>
.horizontal-snap {
margin: 0 auto;
display: grid;
grid-auto-flow: column;
gap: 1rem;
height: calc(180px + 1rem);
padding: 1rem;
max-width: 480px;
overflow-y: auto;
overscroll-behavior-x: contain;
scroll-snap-type: x mandatory;
}
.horizontal-snap > a {
scroll-snap-align: center;
}
.horizontal-snap img {
width: 180px;
max-width: none;
object-fit: contain;
border-radius: 1rem;
}