In this example, a scroll timeline named --myScroller
is defined using the scroll-timeline-name
property on the element with the scroller
class (the scrolling element). This is then applied to the animation on the element with the box
and animation
classes (the animated element) using animation-timeline: --myScroller
. The key point to note here is that the animated element is not a descendant of the scrolling element — to make this work, we increase the scope of the --myScroller
timeline by setting timeline-scope: --myScroller
on the <body>
.
HTML
The HTML for the example is shown below.
<div class="content">
<div class="box animation"></div>
</div>
<div class="scroller">
<div class="long-element"></div>
</div>
CSS
The CSS is as follows.
First of all, we set the <body>
's height to 100vh
, and lay its two child elements out as two equal columns using flexbox. We also set timeline-scope: --myScroller
on it so that the --myScroller
timeline can be set as the controlling timeline for an animation set on the <body>
and any element inside it.
body {
margin: 0;
height: 100vh;
display: flex;
timeline-scope: --myScroller;
}
.content,
.scroller {
flex: 1;
}
Next, the scrolling element has the --myScroller
timeline set on it, overflow
so that it will scroll, and it is given a background color so that its boundary is clear to see. The scrolling element's child long element is given a large height so that the scrolling element will actually scroll.
.scroller {
overflow: scroll;
scroll-timeline-name: --myScroller;
background: deeppink;
}
.long-element {
height: 2000px;
}
Next, we give the animated element some rudimentary styling, and apply an animation to it. We also apply the --myScroller
timeline to it using animation-timeline: --myScroller
. To reiterate, this is only possible because earlier we set timeline-scope: --myScroller
on the <body>
element — the animated element is not a descendant of the scrolling element.
.box {
width: 100px;
height: 100px;
border-radius: 10px;
background-color: rebeccapurple;
position: fixed;
top: 20px;
left: 0%;
}
.animation {
animation: rotate-appear;
animation-timeline: --myScroller;
}
@keyframes rotate-appear {
from {
rotate: 0deg;
left: 0%;
}
to {
rotate: 720deg;
left: 100%;
}
}
Result
Scroll the vertical bar on the pink area to see the square animate.