Hacker News 中文摘要

RSS订阅

CSS原生视差效果 -- CSS-Native Parallax Effect

文章摘要

文章介绍了利用CSS原生滚动驱动动画实现视差效果的新方法。相比传统JavaScript方案,CSS方案性能更好(脱离主线程运行),代码更简洁,只需少量声明式样式即可实现。文中提供了核心CSS代码示例,通过view-timeline和animation-timeline等属性控制动画效果。

文章总结

标题:实用技巧 | 原生CSS实现的视差效果

来源:https://dan-webnotes.com/posts/2026-06-02-css-native-parallax-effect/

2026年6月2日

视差效果历史悠久,虽然实现方式众多,但最新通过CSS滚动驱动动画时间轴技术,我们有了纯CSS的实现方案。

传统方案依赖JavaScript的滚动事件监听器,需要逐帧计算元素位置。而滚动驱动动画完全通过CSS实现,具有性能优势(脱离主线程运行)和代码简洁性,只需一个工具类即可应用。以下是核心代码:

```css .parallax { view-timeline-name: --parallax-tl; view-timeline-axis: block; overflow: hidden;

& > * {
    scale: calc(1 + var(--parallax-offset, 20) * 2 / 100);
    animation: parallax auto linear both;
    animation-timeline: --parallax-tl;
    animation-range: cover;
    will-change: translate;
}

}

@keyframes parallax { from { translate: 0 calc(var(--parallax-offset, 20) * -1%); } to { translate: 0 calc(var(--parallax-offset, 20) * 1%); } } ```

技术要点: 1. view-timeline-name创建基于元素滚动位置的进度时间轴 2. 子元素通过animation-timeline绑定时间轴 3. 默认实现20%的垂直位移,通过缩放(140%)避免留白 4. 使用CSS变量--parallax-offset统一控制位移和缩放比例

注意事项: - 必须单独声明animation-timeline且置于动画简写之后 - 建议添加will-change: translate优化性能 - 应通过媒体查询为prefers-reduced-motion用户禁用效果:

css @media (prefers-reduced-motion: reduce) { .parallax > * { animation: none; scale: 1; } }

参考资源: - Chrome开发者文档 - MDN滚动驱动动画指南 - scroll-timeline属性文档

(注:原文中的HTML示例代码和部分技术细节说明已整合到上述要点中,保持了核心技术的完整说明,同时删减了部分重复性描述。)

评论总结

评论总结:

  1. 期待示例展示
  • 多位用户希望文章能直接包含交互式示例 "That sounds interesting but it would be a whole lot more interesting if the page was itself an example" (baliex) "Hey, where's the demo?" (tantalor)
  1. 与传统CSS视差效果比较
  • 用户讨论新API与传统CSS perspective方法的优劣 "How does this compare to the classic css-native parallax effect?" (mpeg) "Using css perspective for parallax has been around for years and is much simpler code" (geuis)
  1. 技术实现讨论
  • 有用户分享CSS滚动动画的平滑体验 "You can make some really cool stuff with css scroll animations" (thomasikzelf)
  • 对新API功能提出改进建议 "one feature I wish existed is damping" (mrcsmcln)
  1. 浏览器兼容性问题
  • 关注Firefox对功能的支持延迟 "just wish Firefox would get off the flag already" (rohitsriram) "FF was the first browser to have it...now is the only one without it" (Semaphor)
  1. 用户体验问题
  • 部分用户反映效果会导致不适 "I find the effect disorienting" (iama_peasant) "I get motion sickness from this specific effect" (hit8run)
  • 强调应尊重用户偏好设置 "glad the author mentions disabling it respecting user settings" (duskdozer)