:target-within
Experimental: This is an experimental technology
Check the Browser compatibility table carefully before using this in production.
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.)
/* Selects a when one of its descendants is a target */
div:target-within {
background: cyan;
}
Syntax
:target-within {
/* ... */
}
Examples
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
Table of Contents
My Fun Article
You can target this paragraph using a URL fragment. Click on the link
above to try out!
This is another paragraph, also accessible from the links above.
Isn't that delightful?
CSS
article:target-within {
background-color: gold;
}
/* Add a pseudo-element inside the target element */
p:target::before {
font: 70% sans-serif;
content: "►";
color: limegreen;
margin-right: 0.25em;
}
/* Style italic elements within the target element */
p:target i {
color: red;
}
Result
Specifications
Specification |
---|
Selectors Level 4 # target-within-pseudo |
Browser compatibility
Currently, no browsers have implemented this feature.