Use Scoped CSS Variables to Stagger CSS Animations

Jhey Tompkins
InstructorJhey Tompkins
Share this video with your friends

Social Share Links

Send Tweet
Published 3 years ago
Updated 3 years ago

Using CSS variable scope we can stagger CSS animations to our choosing. For our Tic Tac Toe board, we want to stagger the animation of the grid lines in a way that makes it look hand drawn.

Jhey Tompkins: [0:00] Let's stagger the animation of these lines, so it appears like they're hand drawn. To do this, we're going to use inline CSS variables to define an animation delay for each line. To work out the delays, we can use DevTools to see which order we want. We want to animate the first line first, then the third line, then the fourth line, and then the second line.

[0:22] Let's create an array named DELAYS. This will act as a map of delay multipliers for the lines we render. For example, the first line we render will have a delay of , but the third line will have a delay of 1 * whatever we choose the delay step to be. This could be the draw-speed.

[0:40] To apply that delay as an inline CSS variable, let's set delay to DELAYS, and then DELAYS [l] . Our delays currently have no effect, so we need to apply an animation delay. We're going to apply an animation delay of var(--delay) with a fallback of , and then * var(--draw-speed). We're going to use the draw-speed as the stagger for our delays.

[1:03] When we refresh the page, our lines are drawn in in sequence. However, our crosses still don't have that stagger. To fix this, we can use a scoped delay variable on any path that is nth-of-type(2), which will be the second part of our cross. If we set delay to 1 and now we try this in our demo, you can see that the cross is staggered.

[1:24] In review, we can use animation delay with scoped CSS variables to create staggered animation. In this example, we're staggering the lines as they get drawn in and then we're staggering a cross being drawn.

egghead
egghead
~ 42 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today