I was using scroll animation libraries for appearing elements when they appear in the viewport.
Recently, I discovered a way to do it using CSS only.
animation-timeline : view();
This is an experimental property, that not all the browser supports for as of now. But when you specify a value of view() then the animation only triggers when the element comes into viewport
Source: MDN
animation-range
We can use a property called animation-range with your animation to specify when to start and end your animation.
animation-range is a shorthand property for animation-range-start and animation-range-end.
animation-range : start end;
Source: MDN
Assume we have this animation
@keyframes appear {
from {
opacity: 0;
transform: scale(0.5);
}
to {
opacity: 1;
transform: scale(1);
}
}
This animation makes the element appear in the screen, then when you apply this animation to the HTML elements, it will immediately reflect to all the elements.
To specifically tell the browser to run this animation only when the elements appear in the screen, you can use animation-range.
div{
animation: appear linear;
animation-timeline: view();
animation-range: entry 0% cover 40%;
}
The above CSS rules specify that start the animation when elements enter 0% and complete it by it covers 40% in the viewport.
Live sample:
You can modify the animation as per your need like clipping or moving the elements from left to right to animate.