大家好,我是 Just,这里是「设计师工作日常」,今天分享的是当鼠标悬浮在按钮上方时,按钮背景色从左往右滑动变化一个变化切换按钮。
《有趣的css》系列最新实例通过公众号「设计师工作日常」发布。
整体效果
知识点:
①熟悉:before
伪选择器的使用
②熟悉transition
过渡属性
思路:绘制按钮,通过
:before
增加要变化背景色块,然后给:before
伪选择器设置transition
过渡属性。
核心代码部分,简要说明了写法思路;完整代码在最后,可直接复制到本地运行。
核心代码
html 代码
<button class="btn41">鼠标悬浮看效果</button>
button
标签作为按钮主体。
css 部分代码
.btn41{
width: 140px;
height: 50px;
font-size: 14px;
font-weight: 700;
border: none;
background-color: #2c3754;
color: #ffffff;
position: relative;
cursor: pointer;
z-index: 0; /*注意图层前后顺序*/
}
.btn41:before{
content: '';
width: 0;
height: inherit;
position: absolute;
top: 0;
left: 0;
background-color: darkred;
z-index: -1; /*注意图层前后顺序*/
transition: all 0.4s;
}
.btn41:hover:before{
width: 100%;
}
页面中
button
为按钮主体,样式中通过:before
伪选择器添加一个新的背景元素,并且设置transition
过渡属性相关参数,最后添加:hover
状态,当鼠标悬浮到按钮上时,其背景元素宽度变成 100%。
完整代码如下
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="btn41">鼠标悬浮看效果</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;
}
.btn41{
width: 140px;
height: 50px;
font-size: 14px;
font-weight: 700;
border: none;
background-color: #2c3754;
color: #ffffff;
position: relative;
cursor: pointer;
z-index: 0;
}
.btn41:before{
content: '';
width: 0;
height: inherit;
position: absolute;
top: 0;
left: 0;
background-color: darkred;
z-index: -1;
transition: all 0.4s;
}
.btn41:hover:before{
width: 100%;
}
页面渲染效果
以上就是所有代码,以及简单的思路,希望对你有一些帮助或者启发。
[1] 原文阅读
CSS 是一种很酷很有趣的计算机语言,在这里跟大家分享一些 CSS 实例 Demo,为学习者获取灵感和思路提供一点帮助,希望你们喜欢。
我是 Just,这里是「设计师工作日常」,求点赞求关注!