Staggered Animations with CSS Custom Properties

Paul Hebert on the Paul Hebert blog:

Movement in nature doesn’t happen all at once. Imagine a flock of birds taking off, raindrops splashing on the ground, or trees bending in the wind. The magic of these moments comes from many small movements overlapping and converging. I wanted to bring this natural movement into my web animations.

Instead of setting an incremental transition-delay on each :nth-of-type() element to achieve this effect, a different approach was taken: the transition-delay was set once and CSS Custom Property is used as a multiplier to increase that delay per element.

<li class="Menu__item">
  <a href="#" class="Menu__link" style="--index: 0;">Babar</a>
</li>
<li class="Menu__item">
  <a href="#" class="Menu__link" style="--index: 1;">Dumbo</a>
</li>
<li class="Menu__item">
  <a href="#" class="Menu__link" style="--index: 2;">Echo</a>
</li>
<!-- etc. -->
.Menu__link {
  --index: 0;
  transition-delay: calc(0.025s * var(--index));
}

Here’s a pen with the final result:

[CODEPEN EMBED]

Staggered Animations with CSS Custom Properties →

💡 You can also use CSS Custom Properties as binary conditions for your styles. Combine it with a media query such as prefers-reduced-motion and you can disable animations that way.

💁‍♂️ Did you know the part after the : for CSS Custom Properties doesn’t need to be valid CSS? It’s only until it is used that it’ll be evaluated. This fact opens up the way for currying in CSS.

:root {
  --f-2: ((2 / 16 - var(--f-foot)) * var(--f-hill));
}

body {
  font-size: calc(var(--f-2) * 16);
}

Published by Bramus!

Bramus is a frontend web developer from Belgium, working as a Chrome Developer Relations Engineer at Google. From the moment he discovered view-source at the age of 14 (way back in 1997), he fell in love with the web and has been tinkering with it ever since (more …)

Join the Conversation

1 Comment

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.