Measuring a search snippet by width
The output: where a title and a description are cut in a search result, measured in pixels rather than in characters.
- Topics
- Skill areas
- Updated
- ·
Inputs
-
The title and the description as text, each up to 320 characters.
-
The device: desktop or mobile.
-
The result's limits as observed on a date: font size, line width, line count and, on desktop, a pixel budget for the whole text (580 px for a title, 920 px for a description).
Procedure
Measure every character
Each character gets the width it has in the result's typeface at the field's font size; the text's width is the sum. An accented letter takes its base letter's width, and a character outside the table the average lowercase width.
Break into lines
Words fill a line until the next word would pass the line width. The result's line count is the limit.
Cut where the limit falls
On desktop the text is cut when the whole width passes the budget; on mobile when it needs more lines than the result shows. The cut keeps the last whole word and ends with an ellipsis.
Report the fit
The lines as the result shows them, whether the text was cut, the width, the character count and the last word shown before the cut.
Outputs and how to read them
-
The lines as the result shows them; a cut text's last line ends with an ellipsis.
-
Whether the text was cut.
-
The width in whole pixels as if on one line, and the character count.
-
The last word shown before the cut: where a rewrite starts.
Failure modes
-
The search engine changes its layout: the limits carry the date they were checked, and they are the method's only upkeep.
-
A typeface other than the one measured: widths drift by a few percent, enough to move the cut by a word.
-
Characters outside the width table, such as emoji and CJK characters, get an estimate, not a measurement.
-
The cut is an approximation: a text that lands within a few pixels of the limit should be read as cut.
Where it is used
The method is the search snippet preview's code; the prerendered example on that page is computed with the same code at build time.