Skip to content

Software Engineer at Heydoc

Interpolate CSS custom properties values

In recent years CSS Custom Properties have become much more popular. These dynamic CSS runtime-defined slots are powerful, and the browser support is decent. I published “CSS Custom Properties explained” a few years ago, and I highly recommend it if all these are new to you.

CSS transitions and animations are methods to interpolate property values. For example, it allows us to interpolate colours, lengths, angles and other characteristics over time. Wouldn’t it be cool if we could also transition our custom properties using these? Let’s try it out!

div {
  --deg: 0;
  transform: rotate(calc(var(--deg) * 1deg));
  transition: --deg 1s ease-in-out;
}

div:hover {
  --deg: 120;
}

Nice try, but this ain’t gonna work. Let me explain why.

When you interpolate the width of an element, the browser knows how to compute numbers between starting and final stages. Likewise, when you interpolate color, the browser also knows how to determine the shades in between. But, because of the highly permissive syntax for custom property values, the browser has no clue what type of a value it is, so it struggles to determine what should be between the starting and eventual state.

Luckily, the CSS Properties and Values API comes in handy with two methods that allow us to register a property of a particular type, specify the initial value and define its inheritance behaviour. Let’s give it a go one more time, but this time we will provide the browser with a hint about the type of --deg custom property.

@property --deg {
  syntax: "<number>";
  initial-value: 0;
  inherits: false;
}

div {
  --deg: 0;
  transition: --deg 1s ease-in-out;
  transform: rotate(calc(var(--deg) * 1deg));
}

div:hover {
  --deg: 120;
}

An alternative to a CSS @property rule is JavaScript registerProperty() function.

window.CSS.registerProperty({
  name: "--deg",
  syntax: "<number>",
  initialValue: 0,
  inherits: false,
});

Be warned that this is at the experimental stage at the time of writing this article. So please check the browser support for @property before using it on your project.

See the Pen Untitled by Pawel Grzybek (@pawelgrzybek) on CodePen.

Thanks, Lea #

I learned this and a lot more from Lea Verou’s talk “CSS Variable Secrets”, and I highly recommend it to you. Until next time dear friend, stay curious and share knowledge 👋

Leave a comment

👆 you can use Markdown here

Your comment is awaiting moderation. Thanks!