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:
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:
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 properties1 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:
A few things to note:
- 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.
font-variant-numeric
does not work in Internet Explorerfont-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 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
-
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. ↩