Χρησιμοποιούμε cookies για να βελτιώσουμε την εμπειρία σας.

Simplify Your Countdowns: How to Use font-variant-numeric for Consistent Sizing

AG Software Development

2 minutes

Simplify Your Countdowns: How to Use font-variant-numeric for Consistent Sizing

Quite often, we want to implement a countdown or a countup to draw the user's attention or to add some flair to our website / application.

As the numbers inside our container change, we might notice a little shift in the sizing of the container, which is typically caused due to the variable width of the number that is being rendered at the time.

At this point, we might be tempted to play around with setting a specific width for the container holding our value, or maybe combine that with some margin, padding and so on.

These approaches could potentially work, but we would be writing one too many lines.

A reproducible example

As the explanation above might (or might not) be sufficient, I have created a small, reproducible example with React on CodePen. There, you will see that .countup already features font-variant-numeric: tabular-nums and I invite you to comment it out (or remove it completely), to see the container resizing in real-time.

The solution

If we want to solve this quickly, in one line of code, we can do so by setting the CSS property font-variant-numeric to tabular-nums. Alternatively, if we are using TailwindCSS, we can just add tabular-nums to our className.

.countup {
  padding: 2rem;
  width: fit-content;
  height: 100%;
  background: #E2CAD4;
  font-size: 2.5rem;
  font-variant-numeric: tabular-nums;
}

The way it works, is by effectively setting all the figures to be the exact same size, allowing us to either align them or, in our case, avoid any dynamic container resizing. Given how it is well-supported, with over 97% coverage, you might want to keep this in mind in your next (or even current) project.

However, tabular-nums is not the only value that this CSS property accepts and I would highly recommend reading more about it on MDN Web Docs.

A small caveat

The CSS properties font-variant-, also known as OpenType features, have quite a few handy options and can save us from writing a bunch of extra lines. However, we should keep in mind that these features can only be applied to OpenType fonts and might not work as expected for any given font. For more details about OpenType fonts, I would highly recommend reading this article.

Thank you for taking the time to read this article. Happy coding!