I am trying to implement an auto-increasing number animation by CSS following this article.
It works well in my application when opening in Chrome, but in Firefox and Safari, it always shows 0.
Do you have any idea about this problem? Here's the snippet:
@property --num {
syntax: "<integer>";
initial-value: 0;
inherits: false;
}
div {
animation: counter 5s infinite alternate ease-in-out;
counter-reset: num var(--num);
font: 800 40px system-ui;
padding: 2rem;
}
div::after {
content: counter(num);
}
@keyframes counter {
from {
--num: 0;
}
to {
--num: 100;
}
}
<div></div>
The main reason is about @property
in the CSS.
- Firefox: @property
is not supported yet, so we have to use JS to create auto-increasing number. Example:
<div id="counter">0</div>
<script>
function animateCounter(element, start, end, duration) {
let startTime = null;
function updateCounter(currentTime) {
if (!startTime) startTime = currentTime;
const elapsedTime = currentTime - startTime;
const progress = Math.min(elapsedTime / duration, 1);
const currentValue = Math.floor(start + (end - start) * progress);
element.textContent = currentValue;
if (progress < 1) {
requestAnimationFrame(updateCounter);
}
}
requestAnimationFrame(updateCounter);
}
const counterElement = document.getElementById("counter");
animateCounter(counterElement, 0, 100, 5000); // Animates from 0 to 100 in 5s
</script>
- Safari: @property
is supported from v15.4, older version won't work