The ::target-text pseudo-element styles text selected by a supported text-fragment navigation. It is distinct from :target, which matches an element addressed by an ordinary fragment identifier. The browser finds the passage; CSS only paints the resulting text highlight. If the quoted words change or the browser lacks text-fragment support, the passage may not be targeted.
CSS ::target-text: preserve the reader's place after a text-fragment link
When to use it
An investigator shares a paragraph from a lengthy incident report. A restrained highlight gives the recipient a visible landing cue while the paragraph text remains selectable and readable. Use contrasting foreground and background colors and check them under forced colors. The page must still have useful headings and stable section links; a text fragment is a convenience, not the only route to the evidence. Test a fragment that matches one passage, a repeated phrase, a stale quotation, a dark theme, and high zoom. Avoid making the target yellow without considering the text color; inherited pale text can disappear on a bright highlight. This selector cannot identify an arbitrary search result produced by the application, which belongs to a different highlight mechanism. Nor does it mark the passage as semantically important for every reader. If the quotation is part of the report's authored emphasis, preserve that meaning in the document markup.
::target-text { color: #173441; background-color: #ffe29a; }
@media (forced-colors: active) { ::target-text { color: HighlightText; background-color: Highlight; } }Cost and verification
Painting a selected text range is usually modest work; the reliability cost is the fragile match to changing prose. Rewriting a sentence can invalidate old shared links. Keep stable heading anchors for long-lived references and review links that external systems have stored. The stylesheet cannot detect which text directive failed to match. Test the navigation itself, not only a screenshot of the CSS rule. Do not confuse this with :target: one works on targeted text and the other on a fragment-identified element. A text-fragment highlight also does not create focus or an accessible announcement by itself.
Common Mistakes
- Do not rely on a text fragment as the only permanent citation path.
- Do not use :target when the browser targeted text instead of an element.
- Do not assume the highlight creates semantic emphasis.
