Use ::target-text to Locate the Position of '#:~:text=' in the URL

We can see that the URL of some web pages is followed by a: #:~:text=content. Today we will talk about what this is for.

It is a new feature of current browsers. Using it the browser will automatically scroll to the corresponding content position. It is similar to anchor positioning before. Anchor positioning: target must require the page to contain the element with the id of the target. If it doesn't exist, there is no way to locate it. In order to solve this problem, ::target-text appeared!

Grammar

Simply specifying a small text is prone to inaccurate positioning (too easy to repeat). To solve this problem, there are two options.

1. Try to specify as long text as possible so it doesn't repeat itself.

2. Put restrictions around the text, such as starting point characters.

Although option 1 is feasible, it also has problems. One is that the address bar is too long and not very beautiful, and the other is that I only need to share this small piece of content and don't need that much.

Now let's look at option two. Here is a brief introduction to the complete syntax of :~:text.

#:~:text=[prefix-,]textStart[,textEnd][,-suffix]

prefix - prefix text

textStart text start

textEnd text end

-suffix suffix text

Syntactically, only textStart is required, the others are optional. However, it should be noted that if multiple pieces of text can be matched, the first matching text will be located.

Style

In CSS, ::target-text can be used to style this section to highlight scroll-to-text. An example is as follows. However, it supports a limited number of styles. ::target-text is similar to ::selection, only supporting text-related styles.

::target-text {
  background-color: rebeccapurple;
  color: white;
}

Browsers Compatibility

We can see the specific compatibility information on the MDN official website, which requires Chrome 89+ or above.

Browsers Compatibility

Summary

Through this article, you should be able to understand what ::target-text is.

::target-text is similar to :target. They can all jump to the specified location.

::target-text does not need an id and can specify any text.

The address bar matching rule is #:~:text=[prefix-,] textStart [,textEnd] [,-suffix]. Only textStart is required, and others are optional.

Browser support the "Copy link to highlighted content" action, which eliminates the need for manual stitching.

Compatibility is a bit poor. Android users can use it.



Leave a reply



Submit