Skip to content

Instantly share code, notes, and snippets.

@CarterLi
Last active September 23, 2020 08:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CarterLi/f12c58c5481b97a1c31d347e2aa7e834 to your computer and use it in GitHub Desktop.
Save CarterLi/f12c58c5481b97a1c31d347e2aa7e834 to your computer and use it in GitHub Desktop.
Counter Animation Using Pure CSS

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+

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment