CSS Animations 101
Getting up to speed with CSS Animations and why they should be your first choice over JS implementations.
Animations can be an easy way to help engage users but more and more often I'm seeing developers implementing animations in their JavaScript. So I'm going to show you how easy CSS animations are, so that you can start writing animations that don't block your JS thread.
How do I animate with CSS?
CSS animations transition a CSS property between two or more values using keyframes. Keyframes are controls for defining values at different points of an animations runtime.
Live Example - Click text below
I'm sliding in from the right.
There are a couple of useful animations to get you thinking about creating new a more inspired animations yourself. The above example is a simple sliding animation, but what if wanted to create a carousel-style animation where an element just goes round and round... forever?
Combining animation properties
You'll find yourself using some animation properties a lot more than others, I'm going to give you some details on these likely-candidates and you can look up the others yourself over at MDN Web Docs.
The additional properties we're going to play with now are animation-timing-function
and animation-iteration-count
. These properties are pretty on-the-nose about what they do, control the timing and iteration count of the animation.
If we update our animation rule from earlier, we can make it transition linearly (read: smoothly) and loop it until the end of time, or at least until your users get dizzy and close your website!
Live Example #2
I'm sliding in from the right.
Your second CSS animation under your belt in less than 5 minutes? You're a natural at this! 👏
Other useful properties
It's also worth informing you of two more properties that can be very helpful.
The first property is animation-direction
, for a single animation you can set this property to normal (default), reverse, alternate and alternate-reverse. The alternate
value is great for mirroring animations, this is a common use-case for loading animations.
Another useful property is animation-play-state
, which can have the values paused
and running
. This is good for users who prefer reduced motion because you can stop any non-essential animations.
Let's update our animation to alternate animation direction and add an intermediate keyframe to update some extra properties:
Live Example #3 - Alternating slide
I am bouncing from side to side and changing
Compatibility
CSS Animations are widely supported, not just across modern browsers but even by our old friend IE10. You can read more about the exact level of support for all browsers and any known issues at caniuse.com.
Leave a comment
Let me know what else you've learned about CSS animations and what you've built since reading this by leaving a comment or tweeting me.