The :target
CSS pseudo-class represents a unique element (the target element) with an id
matching the URL's fragment.
:target {
border: 2px solid black;
}
For example, the following URL has a fragment (denoted by the # sign) that points to an element called section2
:
http://www.example.com/index.html#section2
The following element would be selected by a :target
selector when the current URL is equal to the above:
<section id="section2">Example</section>
A table of contents
The :target
pseudo-class can be used to highlight the portion of a page that has been linked to from a table of contents.
HTML
<h3>Table of Contents</h3>
<ol>
<li><a href="#p1">Jump to the first paragraph!</a></li>
<li><a href="#p2">Jump to the second paragraph!</a></li>
<li>
<a href="#nowhere">
This link goes nowhere, because the target doesn't exist.
</a>
</li>
</ol>
<h3>My Fun Article</h3>
<p id="p1">
You can target <i>this paragraph</i> using a URL fragment. Click on the link
above to try out!
</p>
<p id="p2">
This is <i>another paragraph</i>, also accessible from the links above. Isn't
that delightful?
</p>
CSS
p:target {
background-color: gold;
}
p:target::before {
font: 70% sans-serif;
content: "►";
color: limegreen;
margin-right: 0.25em;
}
p:target i {
color: red;
}
Result
Specifications
Browser compatibility
|
Desktop |
Mobile |
|
Chrome |
Edge |
Firefox |
Internet Explorer |
Opera |
Safari |
WebView Android |
Chrome Android |
Firefox for Android |
Opera Android |
Safari on IOS |
Samsung Internet |
:target |
1 |
12 |
1 |
9 |
9.5 |
1.3 |
2 |
18 |
4 |
10.1 |
2 |
1.0 |