跳到主要内容

CSS 目标伪类

介绍

CSS 目标伪类(:target)是一种强大的选择器,它允许你根据 URL 的片段标识符(即 URL 中 # 后面的部分)来选择并样式化页面中的特定元素。当用户点击页面内的锚点链接时,目标元素会被选中,并可以应用特定的样式。

什么是片段标识符?

片段标识符是 URL 中 # 后面的部分。例如,在 URL https://example.com/page#section1 中,section1 就是片段标识符。它通常用于指向页面内的特定部分。

基本用法

:target 伪类的基本语法非常简单。你只需要在选择器中添加 :target,然后定义你希望应用的样式。

css
:target {
background-color: yellow;
}

在这个例子中,任何被 URL 片段标识符指向的元素都会有一个黄色的背景。

示例

假设你有一个 HTML 页面,其中包含几个带有 id 的标题:

html
<h2 id="section1">Section 1</h2>
<p>This is the content of section 1.</p>

<h2 id="section2">Section 2</h2>
<p>This is the content of section 2.</p>

<h2 id="section3">Section 3</h2>
<p>This is the content of section 3.</p>

如果你在 CSS 中定义了以下样式:

css
:target {
background-color: yellow;
}

当用户访问 https://example.com/page#section2 时,<h2 id="section2">Section 2</h2> 这个元素将会有一个黄色的背景。

实际应用场景

1. 高亮当前阅读部分

在长篇文章或文档中,可以使用 :target 来高亮用户当前阅读的部分,以提升阅读体验。

css
:target {
background-color: #f0f8ff;
border-left: 5px solid #007bff;
padding: 10px;
}

2. 创建简单的单页应用导航

你可以使用 :target 来创建一个简单的单页应用导航系统。通过点击不同的链接,显示或隐藏不同的内容块。

html
<nav>
<a href="#section1">Section 1</a>
<a href="#section2">Section 2</a>
<a href="#section3">Section 3</a>
</nav>

<div id="section1">
<h2>Section 1</h2>
<p>This is the content of section 1.</p>
</div>

<div id="section2">
<h2>Section 2</h2>
<p>This is the content of section 2.</p>
</div>

<div id="section3">
<h2>Section 3</h2>
<p>This is the content of section 3.</p>
</div>
css
div {
display: none;
}

:target {
display: block;
}

在这个例子中,默认情况下所有的 div 都是隐藏的。当用户点击导航链接时,对应的 div 会显示出来。

注意事项

警告

:target 伪类只能选择当前 URL 片段标识符指向的元素。如果 URL 中没有片段标识符,或者片段标识符没有匹配任何元素,:target 将不会选择任何元素。

提示

你可以结合其他选择器使用 :target,例如 :target h2,来更精确地控制样式。

总结

CSS 目标伪类(:target)是一个非常有用的工具,它允许你根据 URL 的片段标识符来选择并样式化页面中的特定元素。通过合理使用 :target,你可以提升用户体验,创建更动态的页面效果。

附加资源与练习

  • 练习:尝试在你的网页中使用 :target 伪类来高亮当前阅读的部分,或者创建一个简单的单页应用导航系统。
  • 进一步阅读:你可以查阅 MDN Web Docs 了解更多关于 :target 的详细信息。

通过不断实践和探索,你将能够更好地掌握 CSS 目标伪类的使用技巧。