网页 综合 更新时间 2026-11-13 18:54:46

Scroll Animation - CSS-Tricks

自动蜘蛛 css-tricks.com 正文约 2067 字
Scroll Animation - CSS-Tricks
There are some scroll animations that are possible in CSS without any JavaScript at all. Just look at the chapter on the Scroll Indicator, which is clearly CSS magic. But we can do a lot of scroll animation work directly in CSS with just one little bit of information provided by JavaScript: how far the page has scrolled.
So let’s get that out of the way. With a JavaScript one-liner, we can set a CSS custom property that knows the percentage of the page scrolled:
Now we have --scroll as a value we can use in the CSS.
This trick comes by way of Scott Kellum who is quite the CSS trickery master!
Let’s set up an animation without using that value at first. This is a simple spinning animation for an SVG element that will spin and spin forever:
Here comes the trick! Now let’s pause this animation. Rather than animate it over a time period, we’ll animate it via the scroll position by adjusting the animation-delay as the page scrolls. If the animation-duration is 1s, that means scrolling the whole length of the page. is one iteration of the animation.
Try changing the animation-duration to 0.5s. That allows for two complete animation cycles as the page is scrolled down with the animation-delay math.
Scott noted in his original demo that also setting…
… accounted for some “overshoot” weirdness and I can attest that I’ve seen it too, particularly on short viewports, so it’s worth setting these too.
Scott also set the scroll-related animation properties on the :root {} itself, meaning that it could control all the animations on the page at once. Here’s his demo that controls three animations simultaneously:
Join our community of front-end nerds! You'll get into the Discord server and member-only perks and free swag.
Sign up to get front-end roundups, browser updates, and exclusive content sent to your inbox bi-weekly.
Get your t-shirts, prints, stickers, and yes, even mousepads at the brand-spankin' new CSS-Tricks store, now open.
CSS-Tricks is powered by a small team of real-life humans.
Handwritten. Twice a month. No spam. See past issues →
访问原文 返回搜索 https://css-tricks.com/books/greatest-css-tricks/scroll-animation/
本页为82搜索生成的网页快照,内容来自站内索引;演示数据的原文链接仅作示例。