Chips
A chip that wraps should hug its widest line, and since CSS can’t do that, measure the lines and set the width.
The problem
Suggestion chips wrap onto two lines when the panel is narrow. When text wraps, the box stays as wide as its container allows, leaving a slab of empty space beside the words.
The CSS fixes don’t help. width: fit-content uses the unwrapped line as the preferred width. text-wrap: balance evens out the line lengths, but the box still sizes to the container, so you get balanced lines with the same gap beside them.
What I concluded
The browser knows where each line ended up. A Range over the chip’s text returns one rect per line box, so the widest rect plus padding and border is the width the chip should have been.
function hug(chip) {
chip.style.width = ""; // measure the natural wrap
const range = document.createRange();
range.selectNodeContents(chip);
const lines = [...range.getClientRects()];
const tops = new Set(lines.map((r) => Math.round(r.top)));
if (tops.size < 2) return; // one line already hugs
const widest = Math.max(...lines.map((r) => r.width));
const s = getComputedStyle(chip);
const chrome = parseFloat(s.paddingLeft) +
parseFloat(s.paddingRight) + parseFloat(s.borderLeftWidth) +
parseFloat(s.borderRightWidth);
chip.style.width = `${Math.ceil(widest + chrome)}px`;
}
Rules
- Reset before measuring. Clear the width first, or you measure your own last answer.
- Only touch wrapped chips. A single-line chip already fits.
- Re-run when the container changes width. In a layout effect, so it lands before paint.
- Round up. A sub-pixel short and the text re-wraps.
What you get
Chips are tap targets, and a box that matches its text makes it obvious where one suggestion ends and the next begins. It’s a few lines of measuring for a gap CSS has no way to close.
The demo has a toggle and a width slider so you can see the gap appear and close. Related: Clarifying questions.