CSS 伪类 :target 指向一个特定元素,称为 target 元素,其 id 与 URL 中的片段标识符匹配。
语法
:target {
/* css declarations */
}
CSS :target - 链接元素
以下示例演示了如何使用伪类 :target 来突出显示已链接到锚标记的页面部分。
在这里,我们看到 <a> 标签指向 #demo-target1 和 #demo-target2。这分别指向名为 demo-target1 和 demo-target2 的元素。
<html>
<head>
<style>
#demo-target1 {
background-color: yellow;
padding: 10px;
margin: 20px 20px 20px 20px;
}
#demo-target2 {
background-color: lightgray;
padding: 10px;
margin: 20px 20px 20px 20px;
}
#demo-target2:target {
background-color: red;
color: white;
}
#demo-target1:target {
background-color: red;
color: white;
}
</style>
</head>
<body>
<div>
<a href="#demo-target1">Click here to target the ELEMENT-1 and turn its color to red</a>
</div>
<br>
<div>
<a href="#demo-target2">Click here to target the ELEMENT-2 and turn its color to red </a>
</div>
<div id="demo-target1">
<p>This is the target ELEMENT-1 </p>
</div>
<div id="demo-target2">
<p> This is the target ELEMENT-2 </p>
</div>
</body>
</html>
CSS :target - 不存在目标
以下示例演示了伪类 :target 如何不会影响未设置目标的链接。
<html>
<head>
<title>:target with ID</title>
<style>
#demo-target {
background-color: yellow;
padding: 10px;
}
#demo-target:target {
background-color: red;
color: white;
}
</style>
</head>
<body>
<h1>Click on the links below to see the effect of :target with ID</h1>
<ul>
<li><a href="#demo-target">Target Element</a></li>
<li><a href="#other">Other Element</a></li>
</ul>
<div id="demo-target">
<h2>This is the target element</h2>
<p>When this element is the target of the URL fragment identifier, its background color changes to red and the text color changes to white.</p>
</div>
<div id="other">
<h2>This is another element</h2>
<p>This element is not affected by the :target selector.</p>
</div>
</body>
</html>
:target 在 Web 组件中不起作用,因为影子根不会按应有的方式将目标元素传递到影子树中。