Interpolating Numeric CSS Variables

Interpolating Numeric CSS Variables

We can make variables in CSS pretty easily:

:root {
  --scale: 1;
}

And we can declare them on any element:

.thing {
  transform: scale(--scale);
}

Even better for an example like this is applying the variable on a user interaction, say :hover:

:root {
  --scale: 1;
}

.thing {
  height: 100px;
  transform: scale(--scale);
  width: 100px;
}

.thing:hover {
  --scale: 3;
}

But if we wanted to use that variable in an animation… nada.

:root {
  --scale: 1;
}

@keyframes scale {
  from { --scale: 0; }
  to { --scale: 3; }
}

/* Nope! */
.thing {
  animation: scale .25s ease-in;
  height: 100px;
  width: 100px;
}

That’s because the variable is recognized as a string and what we need is a number that can be interpolated between two numeric values. That’s where we can call on @property to not only register the variable as a custom property, but define its syntax as a number:

@property --scale {
  syntax: "<number>";
  initial-value: 1;
  inherits: true;
}

Now we get the animation!

You’re going to want to check browser support since @property has only landed in Chrome (starting in version 85) as of this writing. And if you’re hoping to sniff it out with @supports, we’re currently out of luck because it doesn’t accept at-rules as values… yet. That will change once at-rule()becomes a real thing.


Interpolating Numeric CSS Variables originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

We can make variables in CSS pretty easily:

:root {
  --scale: 1;
}

And we can declare them on any element:

.thing {
  transform: scale(--scale);
}

Even better for an example like this is applying the variable on a user …


Interpolating Numeric CSS Variables originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.



Read More Over At CSS Tricks

More Posts

Understanding reality through algorithms

Understanding reality through algorithms Although Fernanda De La Torre still has several years left in her graduate studies, she’s already dreaming big when it comes

The Web is Good Now

The Web is Good Now The video of Chris Coyier’s talk at CascadiaJS 2022 is now available. It’s his first in-person talk in more than

Share This Page

Footer Logo | Essex Web Hosts

Company Number: 13951480