CSS世界之汉堡菜单按钮动画

效果展示

实现思路

使用 transition 过渡属性和 transform 变形属性,让汉堡图标和关闭图标之间进行过渡、变形,形成视觉效果

代码

1
2
3
4
5
<div class="btn-case">
<span class="line"></span>
<span class="line"></span>
<span class="line"></span>
</div>
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
.btn-case{
width: 48px;
height: 36px;
display: block;
position: relative;
cursor: pointer;
}
.btn-case .line{
width: inherit;
height: 4px;
border-radius: 2px;
display: block;
background-color: #3d3d3d;
position: absolute;
top: 0;
transition: all 0.2s ease-in-out;
}
.btn-case .line:nth-of-type(2){
top: 16px;
}
.btn-case .line:nth-of-type(3){
top: 32px;
}
.btn-case:hover .line:nth-of-type(1){
transform: rotate(45deg);
top: 16px;
}
.btn-case:hover .line:nth-of-type(2){
width: 0;
}
.btn-case:hover .line:nth-of-type(3){
transform: rotate(-45deg);
top: 16px;
}

为了方便演示,我使用了鼠标悬浮 :hover 来触发动画,实际业务需要做出一些修改