Using css variables to create smooth animations
Cyd
Posted on March 18, 2019
Creating animations with JavaScript can be really frustrating. You can't actually manipulate the CSS Object Model directly from JavaScript (yet!), but you definitely want to...
Most people today use either the classList
or the style
property of JavaScript to change styles. The problem with both is that they are actually added to the HTML DOM and not directly to the CSS engine. Waiting for Houdini to be widely supported could take a while, and we want to create smoother and better animations now.
So, what can we do?
The answer is CSS variables, or CSS custom properties as some people like to call them. Because while CSS variables are also manipulated via the style
property in JavaScript it's actually much faster in most browsers than using inline styles.
Using event listeners to change the variables is crazy smooth, here's an example I wrote a few weeks ago (using variable fonts, which are also v. cool!):
Another big advantage of CSS variables is that you can set variables on the parent element which all children elements can read, and subsequently also the :before
& :after
pseudo selectors. This does make adding a new variable slower when there are a lot of child elements though!
Especially animations based on mouse position work really well in my opinion:
But what about IE?
So CSS variables are supported among most browsers, except for of course... IE. But seriously, even microsoft is telling people to stop using IE11. As long as you use the animations for enhancement purposes only, your users --even those who torture themselves with IE-- should be fine.
Posted on March 18, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.