CSS text-box Property

The CSS text-box family controls how extra space around text is trimmed relative to font metrics. It can help align headings, labels, and other text more precisely when normal line boxes leave visible space above or below the glyphs.

Why Text Has Extra Space

Line boxes are based on font metrics, not only the visible shapes of letters. That is useful for general text layout but can make optical alignment difficult in tightly designed components.

Use the text-box Shorthand

Example:

.heading {
  text-box: trim-both cap alphabetic;
}

trim-both trims the block-start and block-end edges. cap uses the font's capital-letter height at the start; alphabetic uses the baseline at the end. Descenders may still extend below that baseline, so avoid clipping them with a tight overflow container.

Longhand Concepts

Property Purpose
text-box-trim Controls which sides are trimmed
text-box-edge Chooses the font metric edges used for trimming

Trim a Heading

Example:

<h2 class="card-title">Account Settings</h2>

<style>
.card-title {
  margin: 0;
  text-box-trim: trim-both;
  text-box-edge: cap alphabetic;
}
</style>

This can make the visible text align more tightly with surrounding artwork or component boundaries.

Do Not Replace line-height Blindly

Text-box trimming and line-height solve different problems. Line height controls spacing between line boxes, while text-box trimming changes the edges used around the text content.

Multiline Text

Test multiline text carefully. A setting that looks good for a one-line badge may not be suitable for paragraphs or translated text with different font metrics.

Progressive Enhancement

Example:

.label {
  line-height: 1.2;
}

@supports (text-box-trim: trim-both) {
  .label {
    text-box-trim: trim-both;
    text-box-edge: cap alphabetic;
  }
}

Text-box features are new and font-sensitive. Test the actual fonts, scripts, zoom levels, and browser versions used by your interface.

Conclusion

CSS text-box trimming gives designers more precise control over the space around visible text. Use it for optical alignment where ordinary line-box metrics create unwanted gaps, while keeping readable line height and robust fallbacks.



Found This Page Useful? Share It!
Get the Latest Tutorials and Updates
Join us on Telegram