AtoZ CSS Quick Tip: Keyframe Animations

Guy Routledge
Guy Routledge

This article is a part of our AtoZ CSS Series. You can find other entries to the series here.
View the full screencast and transcript on Keyframe Animations here.

Welcome to our AtoZ CSS series! In this series, I’ll be exploring different CSS values (and properties) each beginning with a different letter of the alphabet. We know that sometimes screencasts are just not enough, in this article I’ve added a new quick tip/lesson about keyframe animations for you.


K is for @keyframes

In this week’s tip, we look at ways to handle vendor prefixes and a quick tip for refactoring your @keyframes into a more condensed format.

We talked a lot about @keyframes in the video about the letter K. Here are some extra tips that you might find useful when working with CSS animations (and any current or future experimental properties).

Tip 1

When setting up your keyframes for an animation, it’s quite common for certain points of the animation to share the same values for particular properties. Instead of having a long list of keyframes, you can combine them into a comma separated list, just like you would with selectors that share the same properties and values.

@keyframes pulse {
  0%, 50% {font-size: 10px;}
  25%, 100% {font-size: 20px;}

/* just like */
h1, h2, h3 {
  font-family: 'Avenir', sans-serif;

Tip 2

Support for CSS animations is very good — at the time of writing the global support is 89.5% and all supporting browsers have both @keyframes and animation unprefixed.

However, to ensure backwards compatibility with Safari 8 and iOS 8.4 and below, you’ll need -webkit vendor prefixes to ensure your animations actually play. Adding these manually can make your code bloated and hard to maintain as every tiny change will need to be replicated in multiple places. This can be prone to human error which is never a good thing.

There are two ways that you can keep your code nice and clean, and also avoid the manual task of duplication.

You could use the -prefix-free JavaScript library by Lea Verou. This takes care of all the prefixing for you, so you just write the unprefixed code, and the script runs in the browser and injects all the necessary prefixes for you based on support for features in the browser currently being used.

Another option is to use Autoprefixer. This is a CSS post-processer that you run after you’ve finished writing your unprefixed code – usually as part of an automated task runner like Grunt or Gulp. Autoprefixer uses info from Caniuse to determine what prefixes are required.

I personally use Autoprefixer with a Gulp task and haven’t written a vendor prefix for months. It’s a great tip to speed up your workflow and works for all CSS properties, not just @keyframes!