If you have experience with animation in other media, CSS animation’s percentage-based keyframe syntax can feel pretty alien, especially if you want to be very precise about timing. This Sass function lets you forget about percentages and express keyframes in terms of actual frames:
@function f($frame) {
@return percentage( $frame / $totalframes )
}
When you create a new @keyframes
at-rule, put the following three variables above it (customize the values for $seconds
and $framerate
but leave $totalframes
as-is):
$seconds: 3;
$framerate: 30;
$totalframes: $seconds * $framerate;
Now just invoke the f
function in place of percentages:
@keyframes rgb {
#{f(0)} { color: red; } // 0 seconds
#{f(30)} { color: green; } // 1 second
#{f(60)} { color: blue; } // 2 seconds
#{f($totalframes)} { color: red; } // 3 seconds
}
When applying the animation to an element, be sure to set the animation-duration
like so:
.television {
animation-name: rgb;
animation-duration: 1s * $seconds;
}
Any time a new @keyframes
at-rule changes up the frame rate or duration from the one before, just add a new set of variables:
$seconds: 4;
$framerate: 24;
$totalframes: $seconds * $framerate;
@keyframes cmyk {
#{f(0)} { color: cyan; } // 0 seconds
#{f(24)} { color: magenta; } // 1 second
#{f(48)} { color: yellow; } // 2 seconds
#{f(72)} { color: black; } // 3 seconds
#{f($totalframes)} { color: cyan; } // 4 seconds
}
.film {
animation-name: cmyk;
animation-duration: 1s * $seconds;
}