Day 7 of the 30 Day Writing Challenge
CSS Animations have been around for a few years now but when they were first introduced you could only use them in Safari (well webkit technically, although they ran at like 9 fps in Chrome in the early days). That didn’t stop me from making these sumo wrestlers but it did make them a novelty that most people couldn’t see. Fast forward to today - Chrome, Firefox, and the IE10pp4 all support hardware accelerated CSS animations. Browser support is already today, especially on mobile, and it will only get better. So why not start using them now? Declaring animations in CSS requires a lot of code, and supporting multiple browsers means repeating a lot of this lengthy code many times over. Here’s how to cope:
Dealing w/ Prefix Hell
Using CSS animations can be a nightmare. Browser prefixes on properties is one thing, but with CSS animations we’re talking about entire prefixed blocks of code containing prefixed properties. No big deal right? Take a look at how much code it took to setup the ‘rocking’ animation I applied to some of my sumo wrestlers:
It takes 15 rules to properly apply and configure the animation on a given element. That’s inconvenient enough – but then it takes a whopping 74 lines of code to define a simple animation with only 3 keyframes. So how do we solve this?
Pre-parsers to the rescue? Not the case - at least not yet. I haven’t seen or found a way to write a SCSS mixin that could handle blocks. I’m fairly sure mixins are not designed to generate entire blocks of CSS nor were they ever intended to do so. Pre-parsers need another solution on top of functions and mix-ins to handle the problem presented by keyframe declarations.
To demonstrate how you can do this, I created a small class in CoffeeScript called Animator:
Now, to define that ‘rocking’ animation that took 74 lines of CSS, we can just define our keyframes in JSON:
The generate method will append the following CSS to the document’s last stylesheet:
The Animator.animate() method will apply the browser prefixed properties for the animationName, animationDuration, animationDelay etc.. All of the prefix handling here is done via Modernizr.prefixed(). If you’re interested in trying it out I’ve posted the source to github with a quick html file to demo.
The important thing to gain from this is that CSS Animations are pretty well supported but difficult to maintain. Like all proprietary properties, managing all of these prefixed rules is a pain point for developers and CSS animations are probably one of the best examples of how much this can get out of hand.