Sub topic 3
Named Timelines with `scroll-timeline` and `view-timeline`
This chapter assumes you know CSS selectors, @keyframes, animation properties, overflow, transforms, and opacity.
Named timelines
A named timeline lets several elements use the same scroll progress. scroll-timeline names a scroller and selects its axis. view-timeline names the visibility progress of an element.
.scroller {
height: 300px;
overflow-y: auto;
scroll-timeline: --list block;
}
.card {
view-timeline: --card-view block;
animation: reveal linear both;
animation-timeline: --card-view;
animation-range: entry 0% cover 30%;
}
@keyframes reveal {
from { opacity: 0; transform: translateY(40px); }
to { opacity: 1; transform: none; }
}The --list timeline follows the scroller. Each card’s --card-view timeline follows that card’s movement through the scrollport.
Sharing a timeline with `timeline-scope`
An animation normally resolves named timelines from its ancestor chain. timeline-scope makes a named timeline available to elements outside the scroller’s subtree.
body {
timeline-scope: --list;
}
.indicator {
animation: fill linear both;
animation-timeline: --list;
}Use this when a fixed progress indicator and the scrolling content have different DOM locations.
Progressive enhancement and performance
Scroll-linked motion is progressive enhancement. Keep the content usable without animation, respect reduced-motion preferences, and feature-test the timeline property.
@media (prefers-reduced-motion: no-preference) {
@supports (animation-timeline: scroll()) {
.card {
animation: reveal linear both;
animation-timeline: view();
}
}
}Prefer transform and opacity. Browsers can usually update them without recalculating layout. Avoid animating dimensions, position, or expensive effects when every scroll update matters.
Patterns and pitfalls
- Put
animation-timelineafter theanimationshorthand because the shorthand resets it. - Check which element owns the scroll container. The root scroller and a nested scroller produce different progress.
- Use
animation-rangewhen the default range starts or ends at the wrong point. - Test short content, long content, touch scrolling, and reduced motion.
- Do not assume a named timeline is visible everywhere. Its scope and DOM position matter.
The JavaScript API
JavaScript provides ScrollTimeline and ViewTimeline for cases where CSS is insufficient.
const timeline = new ScrollTimeline({
source: document.querySelector('.scroller'),
axis: 'block'
});
document.querySelector('.indicator').animate(
{ transform: ['scaleX(0)', 'scaleX(1)'] },
{ timeline, fill: 'both', easing: 'linear' }
);Use CSS first. Use the Web Animations API when timeline creation or animation values must be controlled dynamically.
Exercise
Why might an indicator fail to use a named timeline created inside a scroller?
Show answer
The timeline may be outside the indicator’s ancestor scope. Declare the name with timeline-scope on a shared ancestor.