search
HomeWeb Front-endCSS TutorialAnimating Number Counters

Animating Number Counters

CSS digital animation, for example, imagine a number changing from 1 to 2, then changing from 2 to 3, then changing from 3 to 4, etc., lasting a specified time. It's like a counter, but controlled by the same animation we use to design animations on the web. This can be useful when designing things like dashboards and can add some vitality to the numbers. Surprisingly, this is now possible in CSS without much skill. You can just jump straight to the new solution if you like, but first let's see how we did it in the past .

A rather logical way to animation numbers is to change numbers through JavaScript. We could do a fairly simple setInterval, but here is a more advanced answer that uses a function that accepts the start value, the end value, and the duration, so you can treat it more like an animation:

If we only use CSS, we can use the CSS counter to animate the numbers by adjusting the counts in different keyframes:

Another way is to line all the numbers in a row and animate their positions, showing only one number at a time:

Some of the duplicate code in these examples can use preprocessors like Pug (for HTML) or SCSS (for CSS) that provide loops to make them easier to manage, but deliberately use native code for purposes so that you can see the basic idea.

New CSS Solution

With the latest support for CSS.registerProperty and @property, we can animate CSS variables . The trick is to declare CSS custom properties as integers; this allows you to interpolate them like any other integer (e.g. in a conversion).

 @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);
}</integer>

Important Note: At the time of writing, this @property syntax is supported only by Chrome (and other Chromium kernel browsers such as Edge and Opera), so it is not cross-browser compatible. If you are building a Chrome-only app (such as the Electron app), you can use it right away, otherwise wait. The above mentioned demo has wider support.

The CSS content property can be used to display numbers, but we still need to use counter to convert numbers to strings, because content can only output<string></string> value.

See if we can ease the animation like any other animation? Super cool!

Typed CSS variables can also be used in @keyframes:

A disadvantage? Counters only support integers. This means that decimals and fractions are not considered. We have to display the integer part and the decimal part separately in some way.

Can we animate decimals?

You can convert decimals (such as --number) into integers. Here is how it works:

  1. Register one<integer></integer> CSS variable (for example --integer) and specify initial-value.
  2. Then use calc() to round: --integer: calc(var(--number))

In this case, --number will round to the nearest integer and store the result in --integer.

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

Sometimes we only need integer parts. There is a clever way to do this: --integer: max(var(--number) - 0.5, 0). This applies to positive numbers. This method doesn't even require calc().

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

We can extract the fractional part in a similar way and then convert it to a string using a counter (but remember that the content value must be a string). To display the connected string, use the following syntax:

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

Here is a complete example of animating with decimal percentages:

Other tips

Because we are using CSS counters, the format of these counters can be in other formats than numbers. Here is an example of animating the letter "CSS" into "YES"!

Oh, and another trick: we can debug the value of the custom attribute through JavaScript:

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

That's it! Today's CSS features are amazing.

The above is the detailed content of Animating Number Counters. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Iterating a React Design with Styled ComponentsIterating a React Design with Styled ComponentsApr 21, 2025 am 11:29 AM

In a perfect world, our projects would have unlimited resources and time. Our teams would begin coding with well thought out and highly refined UX designs.

Oh, the Many Ways to Make Triangular Breadcrumb Ribbons!Oh, the Many Ways to Make Triangular Breadcrumb Ribbons!Apr 21, 2025 am 11:26 AM

Oh, the Many Ways to Make Triangular Breadcrumb Ribbons

SVG Properties in CSS GuideSVG Properties in CSS GuideApr 21, 2025 am 11:21 AM

SVG has its own set of elements, attributes and properties to the extent that inline SVG code can get long and complex. By leveraging CSS and some of the forthcoming features of the SVG 2 specification, we can reduce that code for cleaner markup.

A Few Functional Uses for Intersection Observer to Know When an Element is in ViewA Few Functional Uses for Intersection Observer to Know When an Element is in ViewApr 21, 2025 am 11:19 AM

You might not know this, but JavaScript has stealthily accumulated quite a number of observers in recent times, and Intersection Observer is a part of that

Revisting prefers-reduced-motionRevisting prefers-reduced-motionApr 21, 2025 am 11:18 AM

We may not need to throw out all CSS animations. Remember, it’s prefers-reduced-motion, not prefers-no-motion.

How to Get a Progressive Web App into the Google Play StoreHow to Get a Progressive Web App into the Google Play StoreApr 21, 2025 am 11:10 AM

PWA (Progressive Web Apps) have been with us for some time now. Yet, each time I try explaining it to clients, the same question pops up: "Will my users be

The Simplest Ways to Handle HTML IncludesThe Simplest Ways to Handle HTML IncludesApr 21, 2025 am 11:09 AM

It's extremely surprising to me that HTML has never had any way to include other HTML files within it. Nor does there seem to be anything on the horizon that

Change Color of SVG on HoverChange Color of SVG on HoverApr 21, 2025 am 11:04 AM

There are a lot of different ways to use SVG. Depending on which way, the tactic for recoloring that SVG in different states or conditions — :hover,

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.