按钮模版:btn-4

参考 CodePen 首页按钮实现的

效果展示

实现思路

使用 ::before 伪元素绘制了一个渐变色背景

在鼠标悬停时,使用 animation 属性给 ::before 伪元素添加了一个 flow 动画,使其渐变色背景从左至右流动

这个动画使用 translateX 函数来实现,让渐变色背景在 X 轴上平移

为了使文字不被背景图片遮盖,使用了 z-index 属性为其设置层级

并通过给 span 元素设置背景色和圆角来使其与父元素形状相同

实现代码

1
<button class="btn-4"><span>BTN-4</span></button>
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
@keyframes flow {
0% {
transform: translateX(0);
}
100% {
transform: translateX(-50%);
}
}

.btn-4 {
position: relative;
border-radius: 6px;
color: #fff;
z-index: 2;
overflow: hidden;
padding: 3px;
border: none;
cursor: pointer;
}
.btn-4::before {
content: "";
position: absolute;
top: 0;
left: 0;
width: 200%;
height: 100%;
background: linear-gradient(115deg, #4fcf70, #fad648, #a767e5, #12bcfe, #44ce7b);
background-size: 50% 100%;
}
.btn-4:hover:before {
animation: flow .75s linear infinite;
}
.btn-4 span {
position: relative;
display: block;
height: 100%;
z-index: 2;
padding: 16px 28px;
align-items: center;
background: #000;
border-radius: 3px;
}