Pseudorandom Knowledge

Linking to text fragments

Text fragments allows for linking to any text content in a web page. Text fragments are part of the URL as shown in the examples on this page. In these examples, the syntax for text fragments are shown in red and the texts used are in blue.

https://shakespeare.mit.edu/hamlet/full.html#:~:text=something is rotten

This link opens the text for the Shakespeare play Hamlet, scrolls to the text Something is rotten and highlights it, much like if the user had opened the page and searched for that text themselves. The text is used case insensitively.

https://shakespeare.mit.edu/hamlet/full.html#:~:text=to be,the question

It's also possible to give a start text and an end text where both texts and everything in between is highlighted. This example tries to highlight the text To be, or not to be, that is the question. However, it doesn't work. The problem is that the text to be is found in more than one place. Naturally, the first occurrence will be used which results in this link highlighting too much.

https://shakespeare.mit.edu/hamlet/full.html#:~:text=hamlet-,to be,the question

To solve the problem we can use another text, in this case Hamlet, which must prefix the text we want to search for. This text will not be part of the highlighting, so we end up highlighting just what we want. Note the use of a hyphen at the end of the prefix, this is required.

https://shakespeare.mit.edu/hamlet/full.html#:~:text=hamlet-,to be,the question,-of this straw

It's also possible to use a suffix, like in this example where we once again highlight too much by selecting a later instance of the text the question. Similiarly to the prefix, note the use of a hyphen at the start of the suffix.

https://shakespeare.mit.edu/hamlet/full.html#:~:text=alas%2C poor yorick!

Since the syntax uses commas as separators, any commas in the text we want to search must be URL-encoded. In this example, this highlights the text Alas, poor Yorick!.

index.html#:~:text=highlights-,can be styled with CSS

Text fragment highlights can be styled with CSS on the site where they occur. That is, they can only be styled on the web page that is linked to, it is not possible to style someone else's page.

::target-text {
    color: red;
    background-color: yellow;
}

Only expect text and background colors to be stylable. The documentation for this limitation is a bit vague but it seems to be true in practice.