The :target-within
CSS pseudo-class represents an element that is a target element or contains an element that is a target. A target element is a unique element with an id
matching the URL's fragment. In other words, it represents an element that is itself matched by the :target
pseudo-class or has a descendant that is matched by :target
. (This includes descendants in shadow trees.)
div:target-within {
background: cyan;
}
Highlighting an article
The :target-within
pseudo-class can be used to highlight the article if anything inside it has been directly linked to. The :target
pseudo-class is also being used to show which item has been targeted.
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>
</ol>
<article>
<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>
</article>
CSS
article:target-within {
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-within |
No |
No |
No |
No |
No |
No |
No |
No |
No |
No |
No |
No |