在网页开发中,导航条是最常见的组件之一。借助css的伪类,我们可以在不写javascript的情况下,为导航项添加鼠标悬停、获得焦点等动态视觉效果,让页面更有交互感。

一、基础html结构
先准备一个最简单的横向导航,使用无序列表配合超链接即可:
<nav class="navbar">
<ul>
<li><a href="https://ipipp.com">首页</a></li>
<li><a href="https://ipipp.com/about">关于</a></li>
<li><a href="https://ipipp.com/contact">联系</a></li>
</ul>
</nav>
二、使用hover伪类改变样式
最基础的动态效果就是鼠标移入时改变文字颜色和背景。我们利用a:hover伪类实现:
.navbar ul {
list-style: none;
display: flex;
gap: 20px;
padding: 0;
}
.navbar a {
text-decoration: none;
color: #333;
padding: 8px 12px;
transition: color 0.3s, background 0.3s;
}
.navbar a:hover {
color: #fff;
background: #007bff;
}
三、用before伪类做下划线动画
如果想在悬停时出现一条从左滑出的下划线,可以借助a::before伪元素与hover配合:
.navbar a {
position: relative;
}
.navbar a::before {
content: "";
position: absolute;
left: 0;
bottom: 0;
width: 0;
height: 2px;
background: #007bff;
transition: width 0.3s ease;
}
.navbar a:hover::before {
width: 100%;
}
四、兼顾键盘访问的focus伪类
为了无障碍访问,使用键盘tab切换时也应触发效果,把:focus和:hover写在一起即可:
.navbar a:hover,
.navbar a:focus {
color: #fff;
background: #007bff;
}
.navbar a:hover::before,
.navbar a:focus::before {
width: 100%;
}
五、小结
通过css伪类如hover、focus以及伪元素before,配合transition属性,就能实现导航条的动态效果。这种方式性能好、代码少,适合大多数静态与动态站点。