Understanding Font Metrics and Vertical Alignment for Accurate CSS Vertical Centering
The article explains why common CSS vertical‑centering tricks can leave pixel offsets when fonts differ, details how font metrics such as ascent, descent, and x‑height determine the true baseline, and provides a calculable vertical‑align offset method—while noting its metric‑gathering overhead and anticipating native Houdini support.
Vertical centering is a fundamental CSS issue, but when mixing special fonts or aligning text with icons, standard methods often leave a few pixel offset.
Common vertical‑centering techniques are illustrated with mixed‑font examples, showing that although the methods work in many cases, the visual centering can still be off.
The article then dives into font construction and metrics. It explains concepts such as the EM square, ascent, descent, x‑height, capital height, and line gap, using Arial as a concrete example extracted from FontForge.
Key insight: vertical-align: middle aligns the child element’s midpoint with the parent’s baseline + x‑height/2. Therefore, when the parent’s font-size is set to 0, the baselines coincide, allowing true vertical centering.
When line-height: normal is used, the line height equals content‑area + line‑gap . For Arial (emSize = 2048, ascent = 1854, descent = 434, capitalHeight = 1467, line‑gap = 67) and a font size of 100 px, the rendered height is calculated as (1854 + 434 + 67) / 2048 * 100px = 115px .
const emSize = 2048;
const ascent = 1854;
const descent = 434;
const capitalHeight = 1467;
// font size to be applied
const fontSize = FONT_SIZE;
// compute vertical offset based on font metrics
const verticalAlign = ((ascent - descent - capitalHeight) / emSize) * fontSize;
return (
TEXT
);By applying the computed vertical-align offset, the outer span behaves like a regular inline element while neutralizing differences in font metrics, enabling reliable vertical centering across fonts.
Limitations: the method requires prior knowledge of each font’s metrics. Gathering metrics manually via FontForge is feasible for a few fonts but cumbersome for many. Automated approaches include using Canvas‑based libraries such as FontMetrics.js (which samples rendered glyphs with getImageData ) or parsing font files with opentype.js . Both have performance or accuracy trade‑offs.
Future prospects: CSS Houdini’s Font Metrics draft proposes an API to adjust baseline, em size, and bounding boxes directly, potentially offering a native solution to these typographic alignment issues.
Conclusion: Understanding font metrics clarifies why vertical centering can appear inconsistent and provides a calculable, CSS‑based technique to correct the visual offset.
NetEase Cloud Music Tech Team
Official account of NetEase Cloud Music Tech Team
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.