Ethan Wang, who works at Microsoft:
In a standard text box, there’s almost always extra space above and below the actual text. Because of this, when you use a text box to measure and implement spacing, it ends up larger than you intended. The bigger the line height, the bigger the problem.
You can see the issue below: the 32px
gap between all text ends up too be more than 32px
because of this:
To solve this the new CSS property leading-trim
from the CSS Inline Layout Module Level 3 specification can be used. As per spec:
The
leading-trim
properties allow controlling the spacing above and below the first and last lines of a block. It allows precise control over spacing; moreover, by relying on font metrics rather than hard-coded lengths, it allows content to be resized, rewrapped, and rendered in a variety of fonts while maintaining that spacing.
Vertical Centering of Text is explicitly mentioned in the specification of this new property. Use it as follows:
h1 {
text-edge: cap alphabetic;
leading-trim: both;
}
As Wang notes:
The example above first uses
text-edge
(also a new property) to tell the browser the desired edge of the text is the cap height and the alphabetic baseline. Then it usesleading-trim
to trim it from both sides.These two simple lines of CSS create a clean text box that hugs your text. This helps you achieve much more accurate spacings and create a better visual hierarchy.
Cool! 🤩