:target

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.

:target CSS 伪类表示一个唯一的元素(目标元素),其 id 与当前 URL 片段匹配。

css
/* 选择一个 ID 与当前 URL 片段匹配的元素*/
:target {
  border: 2px solid black;
}

例如,以下 URL 具有一个片段(由 # 符号表示),指向名为 section2 的元素:

url
http://www.example.com/index.html#section2

若当前 URL 等于上面的 URL 时,以下元素将被 :target 选择器被选中:

html
Example

语法

css
:target {
  /* ... */
}

示例

一个目录

:target 伪类可用于高亮显示页面中可从目录中链接到的部分。

HTML

html

目录

  1. 跳转到第一个段落!
  2. 跳转到第二个段落!
  3. 此链接不会跳转,因为目标不存在。

我的趣味文章

你可以使用 URL 片段定位此段落。点击上面的链接试试吧!

这是另一个段落,也可以从上面的链接访问。这不是很愉快吗?

CSS

css
p:target {
  background-color: gold;
}

/* 在目标元素中增加一个伪元素*/
p:target::before {
  font: 70% sans-serif;
  content: "►";
  color: limegreen;
  margin-right: 0.25em;
}

/*在目标元素中使用 italic 样式*/
p:target i {
  color: red;
}

结果

纯 CSS 高亮

你可以不使用任何 Javascript 代码,只使用 :target 伪类创建一个高亮框。该技术依赖于初始化时就隐藏在页面中的链接到指定元素的锚。一旦定位,CSS 就会更改其 display 以便显示它们。

备注: 一个基于 :target 伪类的更为完善的纯 CSS 高亮框可以在 GitHubdemo)上找到。

HTML

html





CSS

css
/* Unopened lightbox */
.lightbox {
  display: none;
}

/* Opened lightbox */
.lightbox:target {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* Lightbox content */
.lightbox figcaption {
  width: 25rem;
  position: relative;
  padding: 1.5em;
  background-color: lightpink;
}

/* Close button */
.lightbox .close {
  position: relative;
  display: block;
}

.lightbox .close::after {
  right: -1rem;
  top: -1rem;
  width: 2rem;
  height: 2rem;
  position: absolute;
  display: flex;
  z-index: 1;
  align-items: center;
  justify-content: center;
  background-color: black;
  border-radius: 50%;
  color: white;
  content: "×";
  cursor: pointer;
}

/* Lightbox overlay */
.lightbox .close::before {
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  position: fixed;
  background-color: rgba(0, 0, 0, 0.7);
  content: "";
  cursor: default;
}

结果

规范

Specification
HTML
# selector-target
Selectors Level 4
# target-pseudo

浏览器兼容性

参见