Have you clicked on a link on Google, and the page scrolled and highlighted the exact text you were reading? Well, this can be done with text fragments.
What are Text Fragments
Text fragments enable linking to specific text on web pages with no ID required. They work by encoding the targeted text and appending it to the URL fragment. When accessed, the browser scrolls to and highlights the specified text to make it clearer.
Text Fragment URL Syntax
Text fragment URLs follow certain syntax:
https://example.com#:~:text=[prefix-,]textStart[,textEnd][,-suffix]
The text fragment starts after the hash part, beginning with the fragment directive :~:
followed by the text directive text=
and one required parameter being the textStart
.
The other optional parameters are:
prefix-
: specifies what text comes BEFORE your targeted text, It’s useful when there are multiple instances of the same text and you need to identify a specific one.textEnd
: marks where you target text ENDS.-suffix
: specifies what text comes AFTER your liked text. Similar toprefix-
, it helps identify a specific instance when there are multiple matches.
Example:
https://douiri.org/blog/margin-padding-visualization/#:~:text=The%20margin%20is,inner%20space%20of%20an%20element Scrolls and highlights the text from “The margin is” till “inner space of an element”
Note that these components must be URL encoded for them to work. The javascript encodeURIComponent()
function can make this step easier by converting each character to its URL-safe format.
Highlighting multiple text fragments on the same page is possible by separating text directives with ampersand &
character
Example:
https://douiri.org#:~:text=about&text=contact Scrolls and highlights both contact and about in the footer
How to Get Text Fragments From your Browser
For now, only Chromium browsers have a built-in method to copy text fragments, on Chrome you can copy text fragments following these steps:
- Select the text you want to link to
- Right-click on the selected text
- From the context menu, press the “copy text to highlight” option.
- Share the copied URL - when others open it, the text will be highlighted.
For browsers lacking a built-in copy option for text fragments, there might be an extension to help you with that.
How to Style Text Fragments Match
CSS provides the ::target-text
pseudo-element to customize the styles of the targeted text. Which is great for matching your theme.
Example:
::target-text {
background-color: pink;
}
This code will change the highlight color to pink.
How to Check Browser Support
To check if text fragments are supported in a browser, you can use the fragmentDirective property from the document object. Here’s an example:
if (document.fragmentDirective) {
// text fragment supported
}
If the feature is not supported, the fragmentDirective property will return undefined.