跳转到内容

background 配合 linear-gradient 实现下划线动画

刀刀
0字
0分钟
2026/8/16

CSS 基础效果

需求:鼠标移动到标题上有一个下划线显示的动画,从左往右。鼠标移出后从左往右隐藏。如果是多行文本他也会按顺序从第一行开始到最后一行结束。

实现该效果,先思索 CSS 中有什么可以跟随行内式盒子移动,首先想到的是背景 background

实现下划线效果,使用背景色不行,因为背景色无法设置宽高。而渐变背景可以,因为渐变背景本质是背景图 background-image ,而背景图可以通过 background-size 设置背景大小。然后再通过 background-position 定位到文字下方。

代码:

css
div {
  background: linear-gradient(to right, #7e2f2b, #146429) no-repeat;
  background-size: 100% 2px;
}

CSS 动画过渡

给下划线添加动画效果,动画的本质就是控制 background-size ,不显示设置 0,显示设置 100%,

代码修改后:

css
div {
  background: linear-gradient(to right, #7e2f2b, #146429) no-repeat left bottom;
  background-size: 0 2px;
  transition: background-size 0.5s;
}

div:hover {
  background-size: 100% 2px;
}

CSS 细节优化

已实现鼠标移入下划线动画显示,移出动画隐藏,但还需优化细节。

动画显示从左到右正确,但是隐藏是从右到左,不是需求的左到右,需要调整。

在设置 background-position 时一开始给它设置的是 left bottom ,所以是从左往右显示,从左往右隐藏。如果修改为 right bottom ,就变成了从右往左显示,从右往左隐藏。

综上,在 hoverbackground-position 设置为 left bottom ,正常状态下设置为 right bottom 即可。

代码:

css
div {
  background: linear-gradient(to right, #7e2f2b, #146429) no-repeat right bottom;
  background-size: 0 2px;
  transition: background-size 0.5s;
}

div:hover {
  background-size: 100% 2px;
  background-position: left bottom;
}

CSS 总体效果

跳转预览:点击跳转

贡献者

The avatar of contributor named as duyidao duyidao
The avatar of contributor named as v_duyilin v_duyilin
The avatar of contributor named as 刀刀 刀刀

页面历史

刀刀博客累计访客 人;文档累计访问量共