Sub topic 1
Scroll-Driven Animations in CSS
Prerequisites
This chapter assumes you know CSS selectors, the cascade, @keyframes, animation properties, overflow, scroll containers, transforms, and opacity.
Recap: keyframes and animation properties
A keyframe animation describes how a property changes between named points. The @keyframes rule defines those points. The animation properties attach the keyframes to an element and control playback.
@keyframes grow {
from { transform: scaleX(0); }
to { transform: scaleX(1); }
}
.progress {
transform-origin: left;
animation: grow 2s ease-out both;
}Here, 2s is the duration, ease-out is the timing function, and both is the fill mode. The fill mode keeps the animation’s styles before and after playback when appropriate.
Time-driven versus scroll-driven animation
A normal animation is time-driven. Its progress depends on elapsed time. After two seconds, the animation reaches its end whether the user is scrolling or not.
A scroll-driven animation uses a timeline based on scroll position. Its keyframes remain ordinary CSS keyframes, but scrolling determines how far through them the browser is. The animation can pause, reverse, or move faster as the user scrolls.
Attaching a timeline with `animation-timeline`
The animation-timeline property chooses the source of animation progress. The scroll() function creates an anonymous scroll progress timeline.
Place animation-timeline after the animation shorthand. The shorthand can reset longhand animation properties, including the timeline.
Scroll progress: a reading progress bar with `scroll()`
This example scales a fixed bar from zero width to full width as the root scroll container moves from its top to its bottom.
@keyframes grow {
from { transform: scaleX(0); }
to { transform: scaleX(1); }
}
.progress {
position: fixed;
inset: 0 0 auto 0;
height: 4px;
background: rebeccapurple;
transform-origin: left;
animation: grow linear both;
animation-timeline: scroll(root block);
}root selects the document’s root scroller. block follows the block direction, usually vertical scrolling. linear keeps the bar proportional to scroll progress.
Exercise
What does scroll(root block) provide to the .progress animation?
Show answer
It provides a timeline whose progress follows vertical scrolling of the root document scroller.