CSS Target Selector Tutorial

In this section, we will learn what the target selector is and how to use it in CSS.

CSS ::target Pseudo Class

First of all, when the id value of an element appears on a URL, that element becomes the target element! This means, if we load the content of that URL, browsers automatically bring the focus of the page to that element. (For example, if the target element is at the bottom of the page, browsers automatically scroll down to make the element become visible to users).

Now, the ::target selector is used to create style and apply that to a target element (the one that its id appeared on the URL).

Example: using ::target pseudo class in CSS

See the Pen using ::target pseudo class in CSS by Enjoy Tutorials (@enjoytutorials) on CodePen.

In the example above, any p element that its ID appears in the URL is considered being the target element.

How Does ::target pseudo class work?

target selector

As the picture above shows, in this example I have selected the “Target the paragraph three” link and as a result of this link selection, the ID of the third paragraph appears in the URL, so now this paragraph is the target and the CSS style of the “p:target” selector applies to this element.

We could be more general and style any element that its ID appears in the URL with only using “:target” as the selector.

Example: using the :target selector in CSS

See the Pen using the :target selector in CSS by Enjoy Tutorials (@enjoytutorials) on CodePen.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies