Recursive AI

Resolve CSS ch and ex units in Go

onehtml-go is a free, open-source HTML parser for Go from Recursive AI, with CSS selectors, computed styles, lossless editing and accessibility checks. MIT or Apache-2.0, no dependencies.

ch uses the advance of 0, and ex uses the height of x. Use WithFontMetrics to supply each measurement as a fraction of the font size, such as XHeight: 0.55 for an x-height that’s 55% of the font size. Requires Go 1.24 or later.

Terminal
go get recursiveai.org/go/onehtml
GO
package main
 
import (
	"fmt"
	"log"
	"strings"
 
	"recursiveai.org/go/onehtml"
)
 
func main() {
	const html = `<p style="font: 20px Demo;
  margin-left: 2ex; padding-left: 3ch">
  Sample text</p>`
	doc, err := onehtml.Parse(strings.NewReader(html))
	if err != nil {
		log.Fatal(err)
	}
	metrics := onehtml.WithFontMetrics(
		func(q onehtml.FontQuery) onehtml.FontMetrics {
			if len(q.Families) > 0 && q.Families[0] == "Demo" {
				return onehtml.FontMetrics{
					XHeight: 0.55, ZeroAdvance: 0.62,
				}
			}
			return onehtml.FontMetrics{}
		},
	)
	node, err := doc.SelectFirst("p")
	if err != nil {
		log.Fatal(err)
	}
	style := doc.Style(metrics).ComputedStyle(node)
	fmt.Println(style.Get("margin-left"))
	fmt.Println(style.Get("padding-left"))
}

Paste the code above into main.go, run go mod init example and go get recursiveai.org/go/onehtml, then go run .; or unzip the example and go run ..

Text
22px
37.2px

The callback supplies example ratios for a font named Demo; no font file is needed. If a requested metric is zero, onehtml-go uses an estimate for that metric.

Variations

To compare with the estimates, add this to the end of main. doc and node are from the example.

GO
estimated := doc.Style().ComputedStyle(node)
fmt.Println(estimated.Get("margin-left"))
fmt.Println(estimated.Get("padding-left"))

The two additional lines are 20px and 30px.

The short answer

Pass a callback to onehtml.WithFontMetrics and pass the option to doc.Style(). Return XHeight for ex and ZeroAdvance for ch, both as fractions of the font size, not pixel values. In the sample, 2ex is 2 × 0.55 × 20px = 22px, and 3ch is 3 × 0.62 × 20px = 37.2px.

What are ch and ex in CSS?

They are font-relative CSS lengths. ch is based on the advance of the digit zero: the space the glyph takes along the line, not the width of its painted outline. ex is based on x-height, the height of the lowercase “x.” A length such as 30ch does not promise that 30 arbitrary characters will fit. In a proportional font, “W” and “i” can advance by different amounts even though a ch length is computed from just one glyph.

Unlike em, which uses the relevant font size, ch and ex depend on the font’s shapes and spacing as well as its size. Changing font family at the same font-size can change padding, margins, and other lengths expressed in those units. Also distinguish rch and rex: they are relative to the root element’s font rather than the local font. The Go metrics hook can supply metrics for both forms.

How do you convert ch and ex to pixels when the font is unknown?

There is no fixed conversion for an arbitrary font. onehtml-go does not load fonts; without a supplied measurement it estimates both units at half an em. For a 20px font, that gives 10px per unit, as shown in the variation. The estimate applies per field: if you know the zero advance but not the x-height, set ZeroAdvance and leave XHeight zero. Treat the estimated lengths as estimates, not measurements of an installed font.

If you do know the font, normalize its metrics to its font size before returning them. For example, an x-height of 11px measured at 20px corresponds to XHeight: 0.55, not XHeight: 11. The style engine applies the font size. A wrong unit in the callback will scale every CSS length that uses the returned metric.

Which font does CSS use for a ch or ex measurement?

Use the primary face your application would draw with. FontQuery gives you the computed list of families in order, plus weight, style, and stretch. The example recognizes only the single family in its input. With a list, use the first family you can supply a face for and choose metrics for the matching face, not one shared set of numbers for every weight or style.

The callback may be called from any goroutine computing styles, and the library keeps its answer per distinct query. Use a concurrency-safe lookup. These values describe the computed CSS lengths; the library does not lay out the page or measure the rendered text.

All onehtml Go recipes