The latest in CSS

The latest in CSS

Create scroll-driven animations

Similar to how time-based animations work on the platform, you can now use a scroller's scroll progress to start, pause, and reverse an animation. So as you scroll forward, you'll see that animation progress, and when scrolling backward it'll go the other way around. This lets you create partial or full-page visuals with elements animating into and within the viewport, also known as scrollytelling, for dynamic visual impact.

@keyframes appear {
 from {
 opacity: 0;
 scale: 0.8;
 }
 to {
 opacity: 1;
 scale: 1;
 }
}

img {
 animation: appear linear;
 animation-timeline: view();
 animation-range: entry 25% cover 50%;
}

The preceding code defines a simple animation that appears in the viewport by changing the opacity and scale of an image. The animation is driven by the scroll position. To create this effect, first set up the CSS animation, and then set the animation-timeline. In this case, the view() function with its default values tracks the image relative to the scrollport (which in this instance is also the viewport).

It's important to keep browser support and user preferences in mind, especially for accessibility needs. Therefore, use the @supports rule to check if the browser supports scroll-driven animations, and wrap your scroll-driven animation in a user preference query like @media (prefers-reduced-motion: no-preference) to respect users' motion preferences. Having made these checks you know that your styles will work, and that the animation is not problematic for the user.

@supports (animation-timeline: view()) {
 @media (prefers-reduced-motion: no-preference) {
 /* Apply scroll-driven animations here */
 }
}
Ratings:

Nov 20, 2024, 3:44 PM

Back to all blogs