Animating Number Counters

Number animation, as in, imagine a number changing from 1 to 2, then 2 to 3, then 3 to 4, etc. over a specified time. Like a counter, except controlled by the same kind of animation that we use for other design animation on the web. This could be useful when designing something like a dashboard, to bring a little pizazz to the numbers. Amazingly, this can now be done in CSS without much trickery. You can jump right to the new solution if you like, but first let’s look at how we used to do it.

One fairly logical way to do number animation is by changing the number in JavaScript. We could do a rather simple setInterval, but here’s a fancier answer with a function that accepts a start, end, and duration, so you can treat it more like an animation:

Keeping it to CSS, we could use CSS counters to animate a number by adjusting the count at different keyframes:

Another way would be to line up all the numbers in a row and animate the position of them only showing one at a time:

Some of the repetitive code in these examples could use a preprocessor like Pug for HTML or SCSS for CSS that offer loops to make them perhaps easier to manage, but use vanilla on purpose so you can see the fundamental ideas.

The New School CSS Solution

With recent support for CSS.registerProperty and @property, we can animate CSS variables. The trick is to declare the CSS custom property as an integer; that way it can be interpolated (like within a transition) just 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);
}

Important Note: At the time of this writing, this @property syntax is only supported in Chrome ( and other Chromium core browsers like Edge and Opera), so this isn’t cross-browser friendly. If you’re building something Chrome-only (e.g. an Electron app) it’s useful right away, if not, wait. The demos from above are more widely supported.

The CSS content property can be used to display the number, but we still need to use counter to convert the number to a string because content can only output <string> values.

See how we can ease the animations just like any other animation? Super cool! 

Typed CSS variables can also be used in @keyframes

One downside? Counters only support integers. That means decimals and fractions are out of the question. We’d have to display the integer part and fractional part separately somehow.

Can we animate decimals?

It’s possible to convert a decimal (e.g. --number) to an integer. Here’s how it works:

  1. Register an <integer> CSS variable ( e.g. --integer ), with the initial-value specified
  2. Then use calc() to round the value: --integer: calc(var(--number))

In this case, --number will be rounded to the nearest integer and store the result into --integer.

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

Sometimes we just need the integer part. There is a tricky way to do it: --integer: max(var(--number) - 0.5, 0). This works for positive numbers. calc() isn’t even required this way.

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

We can extract the fractional part in a similar way, then convert it into string with counter (but remember that content values must be strings). To display concatenated strings, use following syntax:

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

Here’s a full example that animates percentages with decimals:

Other tips

Because we’re using CSS counters, the format of those counters can be in other formats besides numbers. Here’s an example of animating the letters “CSS” to “YES”!

Oh and here’s another tip: we can debug the values grabbing the computed value of the custom property with JavaScript:

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

That’s it! It’s amazing what CSS can do these days.


The post Animating Number Counters appeared first on CSS-Tricks.

You can support CSS-Tricks by being an MVP Supporter.

Displaying the Current Step with CSS Counters

Say you have five buttons. Each button is a step. If you click on the fourth button, you’re on step 4 of 5, and you want to display that.

This kind of counting and displaying could be hard-coded, but that’s no fun. JavaScript could do this job as well. But CSS? Hmmmm. Can it? CSS has counters, so we can certainly count the number of buttons. But how do we calculate only up to a certain button? Turns out it can be done.

Thanks to Jan Enning for emailing in about this trick, it’s very clever!

HTML

It doesn’t have to be buttons; it just needs to be some sibling elements we can count. But we’ll go ahead and use buttons here:

<div class="steps">

  <button class="active">Shop</button>
  <button>Cart</button>
  <button>Shipping</button>
  <button>Checkout</button>
  <button>Thank You</button>

  <div class="message"></div>

</div>

The empty .message div there will be where we output our step messaging with CSS content.

CSS

The trick is that we’re actually going to use three counters:

  1. A total count of all the buttons
  2. A count of the current step
  3. A count of how many remaining steps are after the current step
.steps {
  counter-reset: 
    currentStep 0 
    remainder 0 
    totalStep 0;
}

Now let’s actually do the counting. To count all buttons is straightforward:

button {
  counter-increment: totalStep;
}

Next, we need another thing to count that will also count the buttons. We can use a pseudo-element that’s only purpose is to count buttons:

button::before {
  content: "";
  counter-increment: currentStep;
}

The trick is to stop counting that pseudo-element on all the elements after the active element. If we’re using an .active class that looks like this:

button.active ~ button::before {
  /* prevents currentStep from being incremented! */
  counter-increment: remainder;
}

We’re counting the remainder there, which might also be useful, but because we’re only incrementing the remainder, that means we’re not counting the currentStep counter. Fancy, fancy.

Then we can use the counters to output our messaging:

message::before {
  content: "Step: " counter(currentStep) " / " counter(totalStep);
}

Here it is!

There is a little JavaScript there so you can play with moving the active state on the button, but the counting and messaging is all CSS.

The post Displaying the Current Step with CSS Counters appeared first on CSS-Tricks.

How to Reverse CSS Custom Counters

I needed a numbered list of blog posts to be listed with the last/high first and going down from there. Like this:

5. Post Title
4. Post Title
3. Post Title
2. Post Title
1. Post Title

But the above is just text. I wanted to do this with a semantic <ol> element.

The easy way

This can be done using HTML’ s reversed property on the <ol>:

<ol reversed>
  <li>This</li>
  <li>List</li>
  <li>Will Be</li>
  <li>Numbered In</li>
  <li>Reverse</li>
</ol>

For most people, this would be enough. Job done. 

But I needed custom styles for the counters. 

Let it be known that custom list number styles can be done with the ::marker pseudo-element, but that isn’t yet supported by Chrome (although I hear it’s coming soon).

Because I wanted fully cross-browser compatible custom number styles, I went with custom counters. 

Adding and styling a custom counter

Styling the counters of an ordered list differently from the rest of the list requires disabling the default counters and creating and show our own using CSS Counters. Chris shared a few recipes a while back that are worth checking out.

Assuming we have the following HTML:

<ol class="fancy-numbered">
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
</ol>

…we first need to disable the default counters that come with all ordered lists by setting the CSS property list-style-type to none like so:

ol.fancy-numbered {
  list-style-type: none;
}

That takes out all the default numbering. Next, we create a counter in CSS to track the number of items in the list.

ol.fancy-numbered {
  list-style-type: none;
  counter-reset: a;
}

This gives us a counter named “a” but it can be called it whatever you like. Let’s display our counter using the ::before pseudo-element on the list item (<li>).

ol.fancy-numbered li::before {
  content: counter(a)'.';
}

This will set the content of the pseudo-element to the value of our counter. Right now, that will print 1’s next to your list item.

We need to tell the CSS counter how to increment.

ol.fancy-numbered li::before {
  content: counter(a)'.';
  counter-increment: a;
}

The starting value of “a” is zero, which seems weird, but the default increment is 1, meaning that becomes the actual starting point.  Incrementing up by 1 just happens to be the default, but we can change that as we’ll soon see.

We can now proceed to apply any custom styles we want to the counter, because the counter is just a text pseudo-element that is wide open to styling:

ol.fancy-numbered li::before {
  content: counter(a)'.';
  counter-increment: a;   
  position: absolute;   
  left: 0;   
  color: blue;   
  font-size: 4rem;
}

For example, here, we’ve made the counter color blue and increased the font size. These are things that we couldn’t do using the default counter.

Reversing custom counters

If we add the reversed property to the <ol> element like we did before, we will observe no effect because we disabled the default numbering. That’s just what this property does.

<ol class="fancy-numbered" reversed>
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
</ol>

The code above has no effect on our custom numbering. It’s still probably a good idea to leave it on there, since our intention is to reverse the list. This keeps things semantically accurate.

To reverse the visual order of our counter-based numbering, we need to know the total number of items in the list and instruct the counter to start from that number and then decrement from there.

ol.fancy-numbered {
  counter-reset: a 4;
  list-style-type: none;
}

Here, we’re setting counter-reset to 4. In other words, we’re telling the browser to start the count at 4 instead of 1. We use 4 instead of 3, again, because the counter() rule is applied to the first item on the list, which is 0. But, in the case where we’re counting backwards, 4 becomes our 0. If we started from 3 and decremented, wind up at 0 instead of 1.

Next, we alter our counter-increment rule to decrease by 1 rather than increase, by making it a negative integer.

ol.fancy-numbered li:before {
  content: counter(a)'.';
  counter-increment: a -1;
  position: absolute;   
  left: 0;   
  color: blue;   
  font-size: 4rem;
}

And that’s it! Now the world is your oyster for stuff like step trackers:

Or how about a timeline:

Maybe a business plan?

The post How to Reverse CSS Custom Counters appeared first on CSS-Tricks.

Implement a Counter Table in Elasticsearch

In your product, you ought to know in-depth information concerning feature usage. With that, you also should be interested in knowing when exactly a particular feature was touched last.In this article, we're going to solve the problem of getting click counts on different entities/pages of your website to find out when a particular page last touched.

To solve this problem, two main solutions come to mind: