Demo

Shrinkwrap showdown

With CSS width: fit-content, a bubble whose text wraps is as wide as its max-width, which leaves dead space beside the lines. Pretext finds the tightest width that still wraps to the exact same number of lines.

Container width:

CSS fit-content

Uses width: fit-content and a max-width of 80% of the chat. Text that fits on one line gets a bubble of its own width. Text that wraps gets the whole max-width, however short its lines.

Wasted pixels: ...

Pretext shrinkwrap

Uses layout() to binary-search the tightest width with the same line count, and walkLineRanges() for its widest line. Zero wasted pixels. No DOM text measurement in the resize path.

Wasted pixels: 0

Why can't CSS do this?

CSS picks a box's width before it breaks the lines. fit-content is the width of the text on one line, capped at the room the box may take, here its max-width. If a paragraph is too long for one line and wraps to 3, the box takes all of that room, and stays that wide even when all 3 lines end up shorter. There's no CSS property to say “find the narrowest width that still produces exactly 3 lines.” That requires measuring the text at multiple widths and comparing line counts, which is exactly what Pretext's layout() does, without DOM text measurement in the resize path. Pure arithmetic, no reflows, instant results.