如何在CSS中使用动画制作导航下划线滑动_width与@keyframes结合

答案:通过CSS的::after伪元素创建下划线,利用transition控制width实现鼠标悬停时下划线平滑展开与收起效果,简洁流畅且性能良好。

想让导航菜单的下划线在鼠标悬停时平滑滑动,可以结合 CSS 的 width 属性与 @keyframes 动画来实现。这种方式视觉效果流畅,适合现代网页设计。

基本结构:HTML 导航布局

先构建一个简单的横向导航菜单:


基础样式:设置下划线容器

使用伪元素 ::after 创建下划线,并默认隐藏或设为窄宽度:

.nav-link {
  text-decoration: none;
  color: #333;
  display: inline-block;
  position: relative;
  padding: 10px 15px;
}

.nav-link::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  width: 0;
  height: 2px;
  background-color: #007acc;
  transition: width 0.3s ease;
}

结合 @keyframes 实现滑动动画

定义关键帧动画,控制下划线从左到右展开的过程:

@keyframes underline-slide {
  from {
    width: 0;
  }
  to {
    width: 100%;
  }
}

.nav-link:hover::after {
  animation: underline-slide 0.4s ease forwards;
}

这里使用了 animationforwards 填充模式,确保动画结束后下划线保持 100% 宽度。

优化体验:反向收起动画(可选)

如果希望鼠标移开时也有动画收起效果,可改用 transition 替代 animation:

.nav-link::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  width: 0;
  height: 2px;
  background-color: #007acc;
  transition: width 0.3s ease;
}

.nav-link:hover::after {
  width: 100%;
}

这种方式更简洁,且进出都有过渡效果,无需 keyframes。

基本上就这些。用 @keyframes 能实现更复杂的下划线动画逻辑,比如延迟、弹性效果等,而单纯滑动推荐使用 transition + width,性能更好,代码更清晰。