DEV Community

TusharShahi
TusharShahi

Posted on

HTML Text Fragments πŸͺ„

In HTML, every anchor link acts as a bookmark on the page. Besides acting as a link to another page, it also acts as a checkpoint on that particular page.

Given a page, one can automatically jump to a particular section of the page, like this.

This has been a feature as long as I can remember and has been a convenient way to share resources and engage in conversations.

Text Fragments

Today, I discovered text fragments (available since 2020 in some browsers). With Text Fragments, you can directly link to any portion of text in another web document. The biggest advantage is that it does not matter if the author of the document has annotated it with an ID. All you need to add in the URL is the text.

No more anchors βš“.

This flexibility is amazing and would be a game changer in many fields of work. Here is an example.

The specification mentions that the browser is supposed to highlight the text to make for easy detection.

Popular use cases

Google has embraced the text fragment standard in its search page. The feature is right there. In hindsight, it seems obvious that something like this always existed.

For example, the first result of a search like When did google go ipo always takes you to the exact text with answer.

The search results page:
The search results page

When you click on the first result, you land here:
When you click on the first result, you land here

Syntax

The link is supposed to be of this format:

https://example.com#:~:text=[prefix-,]textStart[,textEnd][,-suffix]
Enter fullscreen mode Exit fullscreen mode

This #:~:text= is slightly different than #, which is for a document fragment.

The support is quite extensive. One can check for textStart, textEnd, and even the prefix & suffix of the text. So it becomes easier to link to a substring when there are multiple instances. Here is an example(pun intended).

Of course, one has the option to decide what the style of a text target looks like with:

::target-text {
background-color: yellow;
}
Enter fullscreen mode Exit fullscreen mode

While the feature is great for website developers, I believe it is as important if you are not a developer and just share/save online documents. Now that 92% of browsers support it, we might see more usage soon.

Top comments (1)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.