Use Scoped CSS Variables to Stagger CSS Animations

Jhey Tompkins
InstructorJhey Tompkins
Share this video with your friends

Social Share Links

Send Tweet

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.