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

当用户点击页面中的锚链接跳转到指定位置时,目标元素可以通过 :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 就会被上述样式修饰。
比如实现一个纯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状态来控制样式的直接方式,不复杂但容易忽略。
以上就是如何在CSS中实现target伪类_锚点元素样式控制的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号