css写一个拟物态的switch按钮
2021-10-23 本文已影响0人
苏苏哇哈哈
1.实现效果
![](https://img.haomeiwen.com/i26325037/bda5c21a84ffa519.gif)
2.实现原理
transform
transition
box-shadow
cubic-bezier
translate3d
label+input[type='checkbox']
3.完整实现代码
<body>
<label class="label">
<div class="switch">
<input class="switch-state" type="checkbox" name="check" value="check" />
<div class="dots"></div>
</div>
<div class="label-text">OFF/ON</div>
</label>
</body>
<style>
body {
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
overflow: hidden;
font-weight: 300;
background-color: #ecf0f3;
}
.label {
display: inline-flex;
align-items: center;
cursor: pointer;
color: #394a56;
}
.label-text {
margin-left: 16px;
transform: rotateY(-180deg);
font-size: 28px;
font-weight: 600;
transition: 3s;
}
.label-text:hover{
transition: 3s;
transform: rotateY(-360deg);
}
.switch {
isolation: isolate;
position: relative;
height: 50px;
width: 100px;
border-radius: 25px;
overflow: hidden;
box-shadow:
-8px -4px 8px 0px #ffffff,
8px 4px 12px 0px #d1d9e6,
4px 4px 4px 0px #d1d9e6 inset,
-4px -4px 4px 0px #ffffff inset;
}
.switch-state {
display: none;
}
.dots {
height: 100%;
width: 200%;
background: #dbdcf3;
border-radius: 25px;
transform: translate3d(-75%, 0, 0);
transition: transform 0.4s cubic-bezier(0.85, 0.05, 0.18, 1.35);
box-shadow:
-8px -4px 8px 0px #ffffff,
8px 4px 12px 0px #d1d9e6;
}
.switch-state:checked~.dots {
transform: translate3d(25%, 0, 0);
}
</style>
4.如有问题,请指正~