Can I Use CSS Variables for Keyframe Timing in Animations?

0
5
Asked By CuriousCoder92 On

I'm curious if CSS variables can be utilized in the timing of keyframes during animations. I've seen them used to adjust properties within animations, but not for the timing itself. For instance, I've set some CSS variables in my code:

:root {
--objCountA: 4%;
--objCountB: 25;
}

And then in my keyframes, I want to use these variables like this:

@keyframes animation {
0% { left: 0; }
var(--objCountA) { left: 50px; }
var(--objCountB)% { left: 75px; }
100% { left: 100px; }
}

My thought was that if the duration each object takes in the animation could depend on how many objects there are, I could just alter the variables instead of re-calculating the keyframe values every time.

**Is this feasible with CSS?** I'm still learning as I mostly work on personal projects, so I haven't dived deep into the core functions of CSS yet. I know I could handle this with JavaScript, but I'd prefer to keep things more concise and contained in one file if possible. If this can be done with CSS, I'm eager to learn!

1 Answer

Answered By WebDevWanderer On

Unfortunately, you can't use CSS variables for keyframe percentages since keyframes are parsed before variables are resolved. You can include variables inside keyframes, but not as selectors for timing. If you want dynamic timing, you'll have to rely on JavaScript to generate your keyframes.

CuriousCoder92 -

Thanks for clearing up the parse timing! I appreciate the explanation.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

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