DEV Community

Cyd
Cyd

Posted on

Using css variables to create smooth animations

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.
Dumbledore shruggs his shoulders

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.

Top comments (4)

Collapse
 
silvandiepen profile image
Sil van Diepen

I feel like I am a part of this... πŸ˜‚

Btw, β€œas some people like to call them”.. that Is what they are called!

Collapse
 
cydstumpel profile image
Cyd

I think CSS variables is easier to understand. :)

Collapse
 
silvandiepen profile image
Sil van Diepen

Yesterday, I wanted to make my point by quoting the website of W3C, but couldnt share the link because invalidate my point. Anyway... ill share it ;)

w3.org/TR/css-variables-1/

The link suggests its called CSS Variables, but the article is about "CSS Custom Properties....". I think they have no idea themselves what it actually should be called.

Thread Thread
 
cydstumpel profile image
Cyd

They're also insinuating that all css variables are custom properties, but not all custom properties are css vars.

"This module introduces cascading variables as a new primitive value type that is accepted by all CSS properties, and custom properties for defining them."