In this example, a scroll timeline named squareTimeline
is defined using the scroll-timeline-name
property on the element with the ID container
. This is then applied to the animation on the #square
element using animation-timeline: squareTimeline
.
HTML
The HTML for the example is shown below.
<div id="container">
<div id="square"></div>
<div id="stretcher"></div>
</div>
CSS
The CSS for the container sets it as the source of a scroll timeline named squareTimeline
using the scroll-timeline
property. It also sets the scrollbar to use for the timeline as "vertical" (though this was not actually needed as it would have been used by default).
The height of the container is set to 300px
, and the container is also set to create a vertical scrollbar if it overflows (the CSS height
rule on the stretcher
element below does make the content overflow its container).
#container {
height: 300px;
overflow-y: scroll;
scroll-timeline: squareTimeline vertical;
position: relative;
}
The CSS below defines a square that rotates according to the timeline provided by the animation-timeline
property, which is set to the squareTimeline
timeline named above.
#square {
background-color: deeppink;
width: 100px;
height: 100px;
animation-name: rotateAnimation;
animation-duration: 1ms;
animation-timeline: squareTimeline;
position: absolute;
bottom: 0;
}
#stretcher {
height: 600px;
background: #dedede;
}
@keyframes rotateAnimation {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
The stretcher
CSS rule sets the block height to 600px
, which creates content that overflows the container element, thereby creating scroll bars. Without this element, the content would not overflow the container, there would be no scrollbar, and hence no scroll timeline to associate with the animation timeline.
Result
Scroll the vertical bar to see the square animate as you scroll.
The square animates as you scroll, and the animation duration when using scroll-timeline
really depends on the scroll speed (nevertheless, the animation-duration
property has been defined so you can make out the scroll-driven animation).