Animated counter is vary useful on dashboard, and implement it with javascript (requestAnimationFrame can be use for performance reasons) is not hard.
But what about a pure CSS solution? It can be done long ago using animation-timing-function: steps(X)
, but the code is verbose and supported range of numbers are very limited.'
With recently supported CSS.registerProperty and @property we could finally animate CSS variables.
@property --num {
syntax: '<integer>';
initial-value: 0;
inherits: false;
}
button {
transition: --num 1s;
&:hover {
--num: 10000;
}
}
content can be used to display text using CSS. But you can't use content: var(--num)
because content
CSS property doesn't support var(--xxx)
syntax at all ( nor is --num
a string ).
counter does the trick. counter() can be used to display the value of a counter and counter-set can be used to set counter to a specified value.
button {
counter-set: num var(--num);
&::after {
content: counter(num);
}
}
A working example: https://codepen.io/CarterLi/pen/bGpmGMN
counter() supports the second parameter to display the counter in various formats. This is an example to animate English words: https://codepen.io/CarterLi/pen/OJNBxNx
Browser support ( as of this writing ): Chrome 85+