:target-within
:target-within
CSS 伪类 代表一个元素,该元素是一个目标元素或 *包含* 一个目标元素。目标元素是一个具有与 URL 片段匹配的 id
的唯一元素。换句话说,它代表一个自身被 :target
伪类匹配或其后代被 :target
匹配的元素。(这包括 阴影树 中的后代。)
css
/* Selects a <div> when one of its descendants is a target */
div:target-within {
background: cyan;
}
语法
css
:target-within {
/* ... */
}
示例
突出显示文章
如果文章内部的任何内容被直接链接,则可以使用 :target-within
伪类来突出显示该文章。:target
伪类也被用来显示哪个项目被选中。
HTML
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
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;
}
结果
规范
规范 |
---|
选择器级别 4 # the-target-within-pseudo |
浏览器兼容性
BCD 表只在浏览器中加载