Trying to make animations that are linked to the user's scroll has always been a pain. It usually requires JavaScript and a lot of it. Putting aside how taxing the process is on CPU and GPU resources, it also requires a lot of calculations and is prone to error. Thankfully, CSS has a solution. We can now use the user's scroll as a timeline for CSS keyframes. To do this, we need to start by defining our keyframes.
@keyframes SlideOut {
0% {
transform: translateX(0%);
}
100% {
transform: translateX(-100%);
}
}
Great! Now if you have ever tried to do scroll linked animations before, you would know that the next step is to build a rather complex JavaScript scroll handler in order to control this animation. However, with the new CSS api, you can simply do this:
.my-element {
animation-name: SlideOut;
animation-timeline: scroll();
animation-range: entry 50% entry 120%;
}
Believe it or not, that is it. Using animation-timeline: scroll() we tell css that we want this animation to not use a time (ie 1000ms) to run the animation but that it should rather be linked to the user's scroll. The second property animation-range: entry 50% entry 100%; tells CSS when to start and when to end the animation.
If you would like to see this in action, you can see and example on my site (watch the title on the left). You can also read more about the api here.