前置知识: CSS

滚动捕捉

00:00
1 min Intermediate 2026/6/14

scroll-snap

1. scroll-snap 概述

CSS 滚动捕捉允许创建类似轮播滚动效果,滚动停止时自动对齐到指定位置

2. 容器属性

.scroll-container {
  scroll-snap-type: x mandatory; /* 方向 + 严格度 */
  overflow-x: auto;
}

scroll-snap-type

方向说明
x水平捕捉
y垂直捕捉
both双向捕捉
说明
mandatory必须捕捉(强对齐
proximity接近时捕捉(默认)

3. 子元素属性

.scroll-item {
  scroll-snap-align: start; /* 对齐方式 */
  scroll-snap-stop: always; /* 停止行为 */
}

scroll-snap-align

说明
start对齐容器起始
center对齐容器中心
end对齐容器结束

scroll-snap-stop

说明
normal可以跳过(默认)
always必须停止

4. 实战:轮播图

.carousel {
  display: flex;
  overflow-x: auto;
  scroll-snap-type: x mandatory;
  scroll-padding: 0 20px;
}

.carousel-item {
  flex: 0 0 100%;
  scroll-snap-align: center;
}

5. 实战:全屏滚动

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

.fullpage-section {
  height: 100vh;
  scroll-snap-align: start;
}

6. scroll-margin 和 scroll-padding

/* 捕捉偏移 */
.snap-item {
  scroll-margin: 80px;
} /* 元素偏移 */
.container {
  scroll-padding: 80px;
} /* 容器偏移 */

知识检测

学习进度

-- 已学文档
--% 知识覆盖率

学习推荐

专注模式