Standardize character width with CSS


Authors note: Before you read this article, you will want to click the “Start timer” button below to enable the live demos. You can cancel it at any time by clicking “Stop timer”.


The width of a character is the amount of horizontal space that it occupies. This width varies between characters, weights, and typefaces. In Lato, for example, the letter W is wider than the letter I.

For most use cases, the varied width of characters isn’t an issue. However, when you are creating an component like a timer, the differences in width can produce some undesirable movements as the numbers change.

Take a look at this example when timer running. Since the characters are all different widths, the number “jitters” around as it increments:

0

This isn’t the end of the world, but it’s not preferable.

To alleviate this, I have in the past turned to monospace typefaces. These allocate the same width for each character, regardless of the space that the stroke needs.

In this example, we can see that the jittering is resolved and the timer increments smoothly:

0

However, altering the typeface might not be the best solution for your product. Especially when the change was only made to prevent the jittering.

Instead, we can use two CSS properties[1] to standardize the character width of an element:

.standardize-character-width {
font-feature-settings: "tnum";
font-variant-numeric: tabular-nums;
}

With those two in place, we can preserve the original typeface and avoid visual jittering:

0

A few things to note:

  1. Adding these properties changes the tracking, or letter spacing, of the characters. This is necessary to standardize widths but might be undesirable for typography aficionados.
  2. font-variant-numeric does not work in Internet Explorer
  3. font-feature-settings supports IE but only works with OpenType fonts

That being said, this is CSS progressive enhancement: for whom it works, it improves the experience. I’m pretty happy with this solution, and I have used it in production with Toollama’s Contraction Tracker.

For more information about the CSS properties, you can read about font-feature-settings and font-variant-numetric on MDN.

Happy standardizing!


Footnotes

  1. I first saw this solution from Tomek Sułkowski (@sulco) on Twitter. He shares lots of great tips like this and is worth the follow. ↩︎

Romans 5:3-5 (SDG)

About

My name is Sean McPherson (SeanMcP), and I am a software engineer based in Pittsburgh, PA. Here I write articles about programming for developers of all levels.