Skip to content

Chrome: visually hidden inline text that must still be copied (Selection.toString) breaks with flex, sr-only, or zero width

Chrome for Testing 151 (headless=new, macOS). A link in rendered text shows a shortened form (label only, or a URL trimmed in the middle) but selecting and copying the surrounding text must yield the full raw source, so the hidden characters stay in the DOM in hidden spans. Expected getSelection().toString() over the anchor (range.selectNode(a)) to equal the raw text. Tried three layouts. (1) Anchor as display:inline-flex with a truncating head span and a fixed tail span: the string came back with a line break between every piece, e.g. https://\ngithub.com/owner/repo/issue\ns/1234\n. (2) Hidden pieces with Tailwind sr-only (position:absolute, 1px clip): toString() was correct but innerText had [\nlabel\n](url), so serializers disagree. (3) Following the usual advice to keep the piece in flow as display:inline-block; width:0; overflow:hidden; white-space:nowrap: no line breaks, innerText correct, but toString() silently dropped the hidden text entirely (max-width:0 and font-size:0 on the inline-block behaved the same).

1 solution
ranked by outcome — not votes
Accepted

Two separate Chrome text-iterator rules are in play.

  1. Block-level boxes emit newlines. Flex and grid items are blockified, and absolutely positioned boxes are block-level too, so any piece laid out that way puts \n into Selection.toString(), innerText, or both. Every piece has to stay inline-level and in flow (inline or inline-block).

  2. Text in a zero-width clipped box is skipped. An inline-block with width:0; overflow:hidden (or max-width:0) contributes nothing to Selection.toString(), even though innerText still includes it. One pixel is enough to keep it.

What works (verified with range.selectNode(a) and selectNodeContents on the parent, both exact):

.copy-only {
  display: inline-block;
  width: 1px;
  margin-right: -1px;   /* give the pixel back */
  overflow: hidden;
  white-space: nowrap;
  vertical-align: bottom;
  color: transparent;   /* the 1px sliver of the first glyph */
}
<a href="https://example.com/a/very/long/path?x=1"><span class="copy-only">https://</span>example.com/a/ve<span class="copy-only">ry/long/pa</span><span aria-hidden="true" class="ellipsis"></span>th?x=1</a>

with .ellipsis::after { content: '…' }: generated content is never copied, so the visible ellipsis does not leak into the clipboard. Trim by characters in markup rather than with text-overflow: ellipsis on a flex child; that is what forces the flex layout in the first place. A plain inline font-size:0 span (not inline-block) is also copied by Chrome, but the 1px inline-block does not depend on minimum-font-size settings.

Also keep whitespace out of the template between the pieces and between sibling components after the anchor; a collapsed space there is rendered and copied.

Not verified in Safari or Firefox.