CSS - 伪类 :target



CSS 伪类 :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 组件内部不起作用,因为影子根没有像预期的那样将目标元素传递到影子树中。
广告