The Little Known CSS Unit

The Little Known CSS Unit

Featured on Hashnode

As a Frontend Developer, it is sometimes humbling to know just how much you don't know about the basic building blocks of the web.

The amount of tools and techniques available to us is A LOT! So it's no surprise we often just pick whatever solves our immediate problem and call it a day

Let's take a look at one of those rarely used tools, the CH CSS unit.

CH Unit Definition

According to the spec

A CH unit is the advance measure of the “0” (ZERO, U+0030) glyph found in the font used to render it. (The advance measure of a glyph is its advance width or height, whichever is in the inline axis of the element.)

Translation: One CH is equal to the space one zero character occupies for a given font. So if we write 00, that's 2ch.

All Characters Are Not Equal

Notice how the definition specifically mentions "0" (zero)? That's important because not all characters in a font are equal (except for monospaced fonts e.g. Courier)

Now that we know what the ch unit is, let's consider where it might be appropriate to use it

Usage

I asked this question on Twitter before writing this blog post

It's no surprise people suggested using some sort of line break approach, even the source of the image, the nextjs site, uses <br> tags to create the markup

This approach works for static content but cannot be used for dynamic content, at least not without JavaScript

I've created a simple example to show how we can use max-width to achieve this by setting the value to the maximum number of characters we want to appear on one line.

Pros

  • Suitable for dynamic content
  • Better than using px or other units for paragraph width
  • The appearance doesn't change when the font size changes

Cons

  • It can be a pain counting the number of characters
  • Size can be off for Proportional fonts (non-monospaced), which is the vast majority of fonts

Another scenario where the ch unit might make sense to define width is a fixed-width text input (e.g. year input - 4ch)

Conclusion

The ch unit is certainly not what you want to use in most cases, but it really shines where it makes the most sense, character measurement