Skip to content

Instantly share code, notes, and snippets.

@robweychert
Last active September 8, 2021 15:19
Show Gist options
  • Save robweychert/5bb3bdc6abcfa906de31945960b68863 to your computer and use it in GitHub Desktop.
Save robweychert/5bb3bdc6abcfa906de31945960b68863 to your computer and use it in GitHub Desktop.
A simple Sass function for frame-based CSS animation

A simple Sass function for frame-based CSS animation

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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment