Sorry, your browser cannot access this site
This page requires browser support (enable) JavaScript
Learn more >

CSS动态下划线

介绍

在完成毕设时,想在网页中添加悬停动态变长的下划线。
而通过text-decoration: underline;设置的下换线无法调整长度。

一顿查询后,发现一个解决方案。
来自 CSS奇思妙想:动态点亮文本下划线 这篇文章。

实现

主要是使用 linear-gradient 生成图片,然后通过将其设置为背景,通过控制背景的宽度、高度与位置来实现。

实例

这是我在毕设中实现的效果。



代码实现比较简单,通过设置背景图片,设置背景图片大小,设置背景图片位置,设置背景图片过渡效果,实现动态下划线。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
<div>
<span id="logo">
欢迎使用
<span id="book"
>&nbsp;BOOK</span><span>&nbsp;</span
>&nbsp;<span id="sight"
><span style="font-size: 7.5px">&nbsp;</span
>议</span
></div
>
<style>
#book {
color: #409eff;
font-weight: bold;
font-style: italic;
}
#sight {
color: #ff9e40;
font-weight: bold;
}
#logo {
font-weight: bold;
text-align: center;
user-select: none;
/* 通过渐变设置图片背景 且不允许重复 */
background: linear-gradient(
to right,
rgb(148.6, 212.3, 117.1),
rgb(179, 224.5, 156.5)
)
no-repeat;
background-size: 0 3px;
/* 背景位置在文字底部 */
background-position: left bottom;
/* 设置平滑过渡效果 */
transition: background-size 0.2s ease-in-out;
}
#logo:hover {
/* 背景宽度变为100% 高度不变 */
background-size: 100% 3px;
/* 可以通过改变背景位置 改变下划线出现和消失的方向 */
background-position: right bottom;
}
</style>


参考资料

CSS奇思妙想:动态点亮文本下划线
linear-gradient

关于本人

HaiYao的博客
Git主页

评论