EP08 | 跟著影片做前端切版練習 - Button Hover Animation Effects

練習影片

練習重點

結構

HTML

1
2
3
4
5
6
7
8
9
10
11
12
13
<body>
<button class="btn btn-fill">
<!--左-->
<span></span>
<!--上-->
<span></span>
<!--右-->
<span></span>
<!--下-->
<span></span>
button
</button>
</body>

CSS

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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
/*使用原生 CSS 變數*/
:root {
--primary: #027be8;
--btn-primary: #36454f;
}
body {
height: 100vh;
background: #565656;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}

.btn {
font-size: 3.5em;
text-transform: uppercase;
color: var(--primary);
/*消除 button 原本樣式*/
appearance: none;
-moz-appearance: none;
-webkit-appearance: none;
outline: none;
border: none;
padding: 20px 40px;
background: var(--btn-primary);
position: relative;
}

.btn-fill span {
position: absolute;
background: var(--primary);
transform: scale(0);
transition: transform 0.3s;
}

/*利用 transform-origin 來設定每個線條的起始點*/
/*從 :hover 到無時適用*/
.btn-fill span:nth-child(1) {
top: 0;
left: 0;
width: 2px;
height: 100%;
transform-origin: top;
}

.btn-fill span:nth-child(2) {
top: 0;
left: 0;
width: 100%;
height: 2px;
transform-origin: right;
transition-delay: 0.3s;
}

.btn-fill span:nth-child(3) {
top: 0;
right: 0;
width: 2px;
height: 100%;
transform-origin: bottom;
transition-delay: 0.6s;
}

.btn-fill span:nth-child(4) {
bottom: 0;
left: 0;
width: 100%;
height: 2px;
transform-origin: left;
transition-delay: 0.9s;
}

.btn-fill:hover {
background: var(--primary);
color: var(--btn-primary);
transition: all 0.3s;
transition-delay: 1.2s;
}

.btn-fill:hover span {
transform: scale(1);
}

/*有 hover 時(滑鼠滑過)套用*/
/*無到有 :hover 時適用*/
/*跟沒 :hover 設定的 transform-origin 方向相反,即可得到展開回收感*/
.btn-fill:hover span:nth-child(1) {
transform-origin: bottom;
}

.btn-fill:hover span:nth-child(2) {
transform-origin: left;
}

.btn-fill:hover span:nth-child(3) {
transform-origin: top;
}

.btn-fill:hover span:nth-child(4) {
transform-origin: right;
}

Demo:

See the Pen EP08 | 跟著影片做前端切版練習 - Advanced CSS Button Hover Animation Effects by Celeste6666 (@celeste6666) on CodePen.