Animating numeric values with CSS

A number counter animates a figure the way other interface elements animate: 1 transitions to 2, 2 to 3, and so on across a set duration. Dashboards are an obvious fit. The long-standing workarounds were JavaScript intervals, CSS counter keyframes, and a strip of digits whose position is animated so only one is visible at a time. Each can be written in a loop-friendly preprocessor, though the examples here stay vanilla so the underlying mechanics remain visible.

Typed custom properties

Recent support for CSS.registerProperty and @property makes CSS variables animatable. Declaring the custom property as an integer is the whole trick: once typed, the value interpolates in a transition like any other integer.

@property --num {
  syntax: '<integer>';
  initial-value: 0;
  inherits: false;
}

div {
  transition: --num 1s;
  counter-reset: num var(--num);
}
div:hover {
  --num: 10000;
}
div::after {
  content: counter(num);
}

The content property displays the result, but it only accepts <string> values, so counters are still needed to convert the number to a string. The animations ease like any other, and typed variables also work inside @keyframes.

Compatibility: at the time of writing, @property is only supported in Chrome and other Chromium-based browsers such as Edge and Opera. It is usable immediately for Chrome-only targets, Electron apps included; otherwise, wait or fall back to the older demos.

Handling decimals

Counters handle integers only, so decimals and fractions cannot be displayed directly. The value must be split into an integer part and a fractional part. To round a decimal such as --number:

  1. Register an <integer> variable (e.g. --integer) with the initial-value specified.
  2. Round with calc(): --integer: calc(var(--number)).

The result is --number rounded to the nearest integer, stored in --integer.

@property --integer {
  syntax: "<integer>";
  initial-value: 0;
  inherits: false;
}
--number: 1234.5678;
--integer: calc(var(--number)); /* 1235 */

When only the integer part is wanted, --integer: max(var(--number) - 0.5, 0) truncates instead, for positive numbers, without needing calc().

/* @property --integer */
--number: 1234.5678;
--integer: max(var(--number) - 0.5, 0); /* 1234 */

The fractional part can be extracted in the same fashion and converted to a string with a counter. Concatenating the strings for display uses the following syntax:

content: "string1" var(--string2) counter(--integer) ...

A complete example animates percentages with decimals.

Beyond plain integers

CSS counters can render formats other than numbers, via list-style-type-style values; one demo animates the letters "CSS" into "YES". For debugging, the computed value of the custom property can be read with JavaScript:

getComputedStyle(element).getPropertyValue('--variable')