In this example, we’ll implement a common feature: animating a simple progress bar to scale from left to right as the user scrolls a web page. Because we want to link our animation to the progress of the root scroller, we can use an anonymous scroll progress timeline.

First let’s define the animation itself. We want our progress bar to scale from left to right, so we’ll use a transform:

@keyframes scaleProgress { 0% { transform: scaleX(0); } 100% { transform: scaleX(1); }
}

To associate our progress bar element’s animation with the progress of scroll, we’ve used the animation-timeline property and set the scroll() function as its value.

.progress { animation-timeline: scroll();
}

The scroll() function allows us to specify the scroll container and axis. The default value is scroll(nearest block), meaning that the animation will be linked to the nearest scrollable ancestor on the block axis. This is sufficient for our purposes, although we could optionally specify the root as the scroll container, since we want to explicitly link the animation to the progress of scroll of the viewport.

.progress { animation-timeline: scroll(root block);
}

Lastly, we need to add our animation to the progress bar element, with our keyframe animation as the animation-name. We need to set the animation duration to auto, as the duration will be determined by the scroll progress. We’re also setting the easing (animation-timing-function) to linear so that it progresses smoothly in line with scroll. If we were to use the default value (ease), the animation would start off slowly before rapidly speeding up, then slowing down at the end — not what we want from a progress indicator!

.progress { animation-timeline: scroll(root); animation-name: scaleProgress; animation-duration: auto; animation-timing-function: linear;
}

We could condense this somewhat using the animation shorthand property:

.progress { animation: scaleProgress auto linear; animation-timeline: scroll(root);
}

Note: animation-timeline is not currently included in the shorthand. However, the animation property resets animation-timeline to auto (the default), so we need to declare animation-timeline after the animation shorthand.

Similar Posts