: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(用于高亮文本片段)