440 private links
Historically, we could link to a certain part of the page only if that part had an ID. All we needed to do was to link to the URL and add the document fragment (ID). If we wanted to link to a certain part of the page, we needed to anchor that part to link to it. This was until we were blessed with the Text fragments!
What are Text fragments?
Text fragments are a powerful feature of the modern web platform that allows for precise linking to specific text within a web page without the need to add an anchor! This feature is complemented by the ::target-text CSS pseudo-element, which provides a way to style the highlighted text.
Text fragments work by appending a special syntax to the end of a URL; just like we used to append the ID after the hash symbol (#). The browser interprets this part of the URL, searches for the specified text on the page, and then scrolls to and highlights that text if it supports text fragments. If the user attempts to navigate the document by pressing tab, the focus will move on to the next focusable element after the text fragment.
How can we use it?
Here’s the basic syntax for a text fragment URL:
https://example.com/page.html#:~:text=[prefix-,]textStart[,textEnd][,-suffix]
Following the hash symbol, we add this special syntax :~: also known as fragment directive then text= followed by:
- prefix-: A text string preceded by a hyphen specifying what text should immediately precede the linked text. This helps the browser to link to the correct text in case of multiple matches. This part is not highlighted.
- textStart: The beginning of the text you’re highlighting.
- textEnd: The ending of the text you’re highlighting.
- -suffix: A hyphen followed by a text string that behaves similarly to the prefix but comes after the text. Aslo helpful when multiple matches exist and doesn’t get highlighted with the linked text.