大家好,我是 Just,这里是「设计师工作日常」,今天分享的是使用 css 模拟拉链打开效果的按钮。
《有趣的css》系列最新实例通过公众号「设计师工作日常」发布。
整体效果
💎知识点:
1️⃣transition
过渡属性
2️⃣:before
和:after
伪元素选择器
3️⃣:hover
选择器
🔑思路:
利用伪元素创建两个矩形,然后改变其宽度以及高度来实现过渡效果。
模拟拉链打开效果的按钮,增强页面按钮的交互感。
核心代码部分,简要说明了写法思路;完整代码在最后,可直接复制到本地运行。
核心代码
html 代码
<button class="btn72">HOVER</button>
按钮主体代码。
css 部分代码
.btn72{
width: 120px;
height: 42px;
font-weight: 600;
font-size: 18px;
line-height: 1;
letter-spacing: 4px;
background: transparent;
border: none;
display: flex;
justify-content: center;
align-items: center;
position: relative;
z-index: 0;
transition: color 0.3s linear;
cursor: pointer;
}
.btn72:before{
content: '';
width: 0;
height: 2px;
background-color: #1630f1;
position: absolute;
left: 0;
z-index: -1;
transition: width 0.3s linear;
}
.btn72:after{
content: '';
width: 100%;
height: 0;
background-color: #1630f1;
position: absolute;
z-index: -1;
transition: height 0.3s linear;
}
.btn72:hover:before{
width: 100%;
}
.btn72:hover:after{
transition-delay: 0.3s;
height: 100%;
}
.btn72:hover{
color: #fff;
transition-delay: 0.3s;
}
1、定义按钮基本样式,设置
flex
布局,设置过渡属性参数transition: color 0.3s linear;
,给字体颜色增加过渡效果。
2、利用
:before
创建一个伪元素矩形,默认宽度为0
,高度为2px
,设置定位属性,让矩形靠左对齐,设置其宽度过渡属性参数transition: width 0.3s linear;
。
3、利用
:after
再创建一个伪元素矩形,默认宽度为100%
,高度为0
,设置定位属性,根据flex
布局平行垂直居中,设置其高度过渡属性参数transition: height 0.3s linear;
。
4、根据
:hover
选择器,让其两个伪元素矩形,变化其宽度和高度数值,:after
伪元素矩形设置过渡延迟时间transition-delay: 0.3s;
,让:after
伪元素矩形在:before
伪元素矩形之后衔接过渡。
5、根据
:hover
选择器,给按钮主体标签添加字体颜色,让按钮文字颜色从黑色过渡到白色,同样设置过渡延迟时间transition-delay: 0.3s;
,让字体颜色在:before
伪元素矩形之后衔接过渡。
完整代码如下
html 页面
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="style.css">
<title>拉链式展开按钮</title>
</head>
<body>
<div class="app">
<button class="btn72">HOVER</button>
</div>
</body>
</html>
css 样式
/** style.css **/
.app{
width: 100%;
height: 100vh;
background-color: #ffffff;
position: relative;
display: flex;
justify-content: center;
align-items: center;
}
.btn72{
width: 120px;
height: 42px;
font-weight: 600;
font-size: 18px;
line-height: 1;
letter-spacing: 4px;
background: transparent;
border: none;
display: flex;
justify-content: center;
align-items: center;
position: relative;
z-index: 0;
transition: color 0.3s linear;
cursor: pointer;
}
.btn72:before{
content: '';
width: 0;
height: 2px;
background-color: #1630f1;
position: absolute;
left: 0;
z-index: -2;
transition: width 0.3s linear;
}
.btn72:after{
content: '';
width: 100%;
height: 0;
background-color: #1630f1;
position: absolute;
z-index: -1;
transition: height 0.3s linear;
}
.btn72:hover:before{
width: 100%;
}
.btn72:hover:after{
transition-delay: 0.3s;
height: 100%;
}
.btn72:hover{
color: #fff;
transition-delay: 0.3s;
}
页面渲染效果
以上就是所有代码,以及简单的思路,希望对你有一些帮助或者启发。
[1] 《有趣的css》,访问网址:funcss.liujueyi.cn,欢迎大家访问。
我是 Just,这里是「设计师工作日常」,求点赞求关注!