:target
:target CSS 偽類選擇“文件的目標元素”。當文件載入時,目標元素是使用文件的URL 片段識別符號派生出來的。
css
/* Selects document's target element */
:target {
border: 2px solid black;
}
例如,以下 URL 有一個片段識別符號(由 # 符號表示),它將 id 為 setup 的元素標記為文件的目標元素
url
http://www.example.com/help/#setup
噹噹前 URL 等於上述 URL 時,以下元素將被 :target 選擇器選中
html
<section id="setup">Installation instructions</section>
語法
css
:target {
/* ... */
}
描述
當 HTML 文件載入時,瀏覽器會設定其目標元素。該元素使用 URL 片段識別符號進行標識。如果沒有 URL 片段識別符號,文件就沒有目標元素。:target 偽類允許對文件的目標元素進行樣式設定。該元素可以被聚焦、高亮、動畫等。
目標元素是在文件載入和呼叫 history.back()、history.forward() 和 history.go() 方法時設定的。但是,當呼叫 history.pushState() 和 history.replaceState() 方法時,它不會改變。
注意:由於CSS 規範中可能存在錯誤,:target 在Web 元件中不起作用,因為影子根不會將目標元素傳遞到影子樹。
示例
目錄
: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>
<li>
<a href="#nowhere">
This link goes nowhere, because the target doesn't exist.
</a>
</li>
</ol>
<h3>My Fun Article</h3>
<p id="p1">
You can target <i>this paragraph</i> using a URL fragment. Click on the first
link above to try out!
</p>
<p id="p2">
This is <i>another paragraph</i>, also accessible from the second link above.
Isn't that delightful?
</p>
CSS
css
p:target {
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;
}
結果
規範
| 規範 |
|---|
| HTML # selector-target |
| 選擇器 Level 4 # target-pseudo |
瀏覽器相容性
載入中…
另見
- 在選擇器中使用 :target 偽類
::target-text(用於高亮文字片段)