:target 伪类可选中URL片段对应的元素并应用样式。例如 #about 会匹配 id 为 about 的元素,常用于高亮导航目标、实现无JavaScript模态框等场景,提升单页交互体验。

当用户点击页面中的锚链接跳转到指定位置时,目标元素可以通过 :target 伪类进行样式控制。这个功能在单页应用或文档内部导航中非常实用,能提升用户体验。
什么是 :target 伪类
:target 是一个CSS伪类,用于选中当前URL片段标识符(即井号 # 后面的部分)所指向的元素。例如,若 URL 为 example.html#section1,则 #section1 元素会匹配 :target 选择器。
基本用法示例
假设你有如下HTML结构:
<nav>
<a href="#home">首页</a>
<a href="#about">关于</a>
<a href="#contact">联系</a>
</nav>
<section id="home"><h2>首页内容</h2></section>
<section id="about"><h2>关于我们</h2></section>
<section id="contact"><h2>联系我们</h2></section>
你可以使用以下CSS高亮当前激活的章节:
立即学习“前端免费学习笔记(深入)”;
:target {
background-color: #ffeb3b;
outline: 2px solid #ffa000;
padding: 10px;
border-radius: 4px;
}
当点击“关于”链接后,URL变为 #about,id为 about 的 section 就会被上述样式修饰。
实用场景与增强效果
- 滚动到锚点时添加淡入、位移动画:配合 transform 和 opacity 实现平滑提示
- 临时高亮标题:帮助用户快速识别跳转位置
- 模态框控制:用 :target 显示隐藏弹窗(无需JavaScript)
比如实现一个纯CSS的轻量级模态框:
<a href="#modal">打开弹窗</a>
<div id="modal" class="modal">
<div class="modal-content">
<p>这是弹窗内容</p>
<a href="#">关闭</a>
</div>
</div>
对应CSS:
.modal {
display: none;
}.modal:target {<br>
display: block;<br>
position: fixed;<br>
top: 0; left: 0;<br>
width: 100%; height: 100%;<br>
background: rgba(0,0,0,0.5);<br>
justify-content: center;<br>
align-items: center;<br>
}
这种方法适合简单交互,避免依赖脚本。
基本上就这些。:target 提供了一种基于URL状态来控制样式的直接方式,不复杂但容易忽略。










