Animate number increments with CSS (Animate CSS @property integer with keyframes)

Viewed 1368

There is a great way to animate a number increase/decrease with just CSS or with the help of the Web Animations API for dynamic values (see the code snippet).

By creating a custom CSS @property as the integer data type - we are able to animate it with keyframes.

It works great until large numbers are used. When the counter passes 999999 – it sets to 0 for anything larger than this number. If I use CSS without javascript - the number is slightly higher but eventually sets to zero as well.

Does anyone have any idea what's the cause. The data type is a 32-bit integer which should work up to 2,147,483,647.

document.getElementById('count1').animate([
  { '--num': 0 },
  { '--num': 10000 },
  { '--num': 999999 }
], {
  duration: 3000,
    fill: 'forwards',
    iterations: 1
});

document.getElementById('count2').animate([
  { '--num': 0 },
  { '--num': 100 },
  { '--num': 1000000 }
], {
  duration: 2000,
    fill: 'forwards',
    iterations: 1
});
@property --num {
  syntax: "<integer>";
  initial-value: 0;
  inherits: false;
}

div {
  counter-set: num var(--num);
  font-size: 40px;
  font-weight: bold;
}

div:after {
  content: counter(num);
}
<div id="count1"></div>
<div id="count2"></div>

1 Answers

I don't know what causes this, but here is a workaround.

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

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

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

div {
  counter-reset: num1 var(--num1) num2 var(--num2) num3 var(--num3);
  font-size: 40px;
  font-weight: bold;
  animation: animate 2s forwards ease;
}

div:before {
  content: counter(num1) counter(num2) counter(num3);
}

@keyframes animate {
  to {
    --num1: 3;
    --num2: 8;
    --num3: 999999;
  }
}
<div></div>

Related