Sequential Linear Animation with N Elements

Imagine you have `N` elements with the same animation that should animate one after the other, looping back to the start after the last one. Achieving this effect can be tricky, requiring complex keyframes and delay calculations. However, with modern CSS, we can accomplish this with just a few lines of code, suitable for any number of items.

Currently, the following demo works in Chrome and Edge, but it will extend to other browsers as the `sibling-index()` and `sibling-count()` functions gain support. Firefox support can be tracked in Ticket #1953973, and WebKit’s position in Issue #471.

In the demo, elements are animated sequentially with simple keyframes that change an element’s background color and scale:

“`css
@keyframes x {
to {
background: #F8CA00;
scale: .8;
}
}
“`

You can add or remove items, and everything continues to work smoothly. This effect is achieved with the following code:

“`css
.container > * {
–_s: calc(100%*(sibling-index() – 1)/sibling-count());
–_e: calc(100%*(sibling-index())/sibling-count());

animation:
x calc(var(–d)*sibling-count()) infinite
linear(0, 0 var(–_s), 1, 0 var(–_e), 0);
}
“`

The CSS `linear()` function allows defining timing functions with multiple points for “linear” interpolation between consecutive points. This enables creating complex animations with simple keyframes.

For sequential animations, each element animates and then “waits” until others finish before starting again. This waiting time acts as a delay, achieved using `linear()`:

“`css
linear(0 0%, 0 50%, 1 100%)
“`

This creates a delay without updating keyframes. Adding more points allows returning to the initial state:

“`css
linear(0 0%, 0 50%, 1 75%, 0 100%)
“`

For `N` elements, the `linear()` function syntax is:

“`css
linear(0, 0 S, 1, 0 E, 0)
“`

Where `S` and `E` are calculated to ensure sequential animations. This is done programmatically using `sibling-count()` and `sibling-index()` functions:

“`css
S = calc(100%*(sibling-index() – 1)/sibling-count())
E = calc(100%*sibling-index()/sibling-count())
“`

With this, you can define animations for any number of elements without complex keyframes.

The `linear()` function, initially for complex easing, combined with modern features, offers many possibilities for creating advanced animations.


Discover more from WIREDGORILLA

Subscribe to get the latest posts sent to your email.

Similar Posts