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 元件內部不起作用,因為影子根沒有像預期的那樣將目標元素傳遞到影子樹中。
廣告