本文详解如何使用 CSS scroll-snap-type 和 scroll-snap-align 实现移动端单页一节、滑动即切换的 TikTok 式垂直分页滚动效果,适配小屏幕(≤550px),无需 JavaScript。
本文详解如何使用 css `scroll-snap-type` 和 `scroll-snap-align` 实现移动端单页一节、滑动即切换的 tiktok 式垂直分页滚动效果,适配小屏幕(≤550px),无需 javascript。
要让 .recipe 区块在移动设备上呈现类似 TikTok 的“一屏一内容”垂直滑动体验(即滑动后自动吸附对齐到下一个完整区块),核心在于 容器级滚动控制 + 子项吸附定位,而非依赖 inline 布局或 white-space: nowrap(后者适用于水平滚动,此处为垂直场景)。
✅ 正确实现要点
-
容器需启用强制垂直吸附
#container 必须设置固定高度(推荐 100vh)、允许纵向滚动,并声明 scroll-snap-type: y mandatory:
@media only screen and (max-width: 550px) {
#container {
height: 100vh;
overflow-y: auto;
overflow-x: hidden;
scroll-snap-type: y mandatory; /* 关键:y轴强制吸附 */
scroll-behavior: smooth; /* 可选:启用平滑过渡 */
}
.recipe {
height: 100vh; /* 与容器等高,确保每节占满一屏 */
scroll-snap-align: start; /* 关键:顶部对齐吸附点 */
scroll-margin-top: 0; /* 可选:微调吸附基准(如需避开 fixed header) */
}
}
移除干扰布局属性
原 CSS 中的 display: inline、white-space: nowrap 和 html { scroll-snap-type: y mandatory } 均不适用——前者破坏块级流式布局,后者作用于根元素会干扰全局滚动行为。应仅对目标滚动容器(#container)设置吸附规则。确保结构语义正确
已是语义化块级元素,无需额外 display 覆盖;只需保证其高度撑满视口即可。
? 完整可运行示例(精简版)
<!-- 在原有 HTML 中,仅需调整 CSS 并确保 container 是直接滚动容器 --> <div id="container"> <section class="recipe">...</section><section class="recipe">...</section><section class="recipe">...</section> </div>
/* 移动端专属样式 */
@media (max-width: 550px) {
html, body {
margin: 0;
padding: 0;
height: 100%;
}
#container {
height: 100vh;
overflow-y: auto;
overflow-x: hidden;
scroll-snap-type: y mandatory;
scroll-behavior: smooth;
/* 隐藏默认滚动条(可选) */
-ms-overflow-style: none;
scrollbar-width: none;
}
#container::-webkit-scrollbar {
display: none;
}
.recipe {
height: 100vh;
scroll-snap-align: start;
padding: 1rem;
box-sizing: border-box;
}
/* 其他响应式文本/图片样式保持不变 */
section h2 { font-size: 2.2rem; }
section h5 { font-size: 1.35rem; }
p { font-size: 1.25rem; }
}
⚠️ 注意事项
- 兼容性:scroll-snap-* 属性在现代浏览器(Chrome 69+、Firefox 68+、Safari 11.1+)中支持良好,iOS Safari 同样可用。
- 性能优化:避免在 .recipe 内使用 transform 或 opacity 动画触发重排;吸附本身为原生滚动优化,性能优异。
- 无障碍支持:保留原生滚动能力,键盘 Page Down/Up 和辅助技术仍可正常导航。
-
Header/Fixed 元素处理:若顶部
为 position: fixed,需为 .recipe 添加 scroll-margin-top: [header-height](如 scroll-margin-top: 64px),防止吸附时被遮挡。
通过以上配置,用户在手机上垂直滑动时,每次松手都会自动“卡”入下一个 .recipe 区块顶部,实现精准、流畅、原生的 TikTok 式浏览体验——简洁、高效、零 JS 依赖。











