The #square
element is animated using an anonymous scrollbar timeline, which is applied to the element to be animated using the scroll()
functional notation. The timeline in this particular example is provided by the nearest parent element that has (any) scrollbar, from the scrollbar in the block direction.
HTML
The HTML for the example is shown below.
<div id="container">
<div id="square"></div>
<div id="stretcher"></div>
</div>
CSS
The CSS below defines a square that rotates in alternate directions according to the timeline provided by the animation-timeline
property. In this case the timeline is provided by scroll(block nearest)
, which means that it will select the scrollbar in the block direction of the nearest ancestor element that has scrollbars; in this case the vertical scrollbar of the "container" element.
Note that the block nearest
options below are actually the default, so we could instead just have had: scroll()
.
#square {
background-color: deeppink;
width: 100px;
height: 100px;
margin-top: 100px;
position: absolute;
bottom: 0;
animation-name: rotateAnimation;
animation-duration: 3s;
animation-direction: alternate;
animation-timeline: scroll(block nearest);
}
@keyframes rotateAnimation {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
The CSS for the container sets its height to 300px and we also set the container to create a vertical scrollbar if it overflows. The "stretcher" CSS sets the block height to 600px, which forces the container element to overflow. These two together ensure that the container has a vertical scrollbar, which allows it to be used as the source of the anonymous scrollbar timeline.
#container {
height: 300px;
overflow-y: scroll;
position: relative;
}
#stretcher {
height: 600px;
}
Result
Scroll to see the square element being animated.