制作css开关
使用纯CSS创建开关
HTML结构需要包含一个隐藏的复选框和一个关联的标签元素:
<label class="switch">
<input type="checkbox">
<span class="slider"></span>
</label>
CSS样式实现滑动动画效果:

.switch {
position: relative;
display: inline-block;
width: 60px;
height: 34px;
}
.switch input {
opacity: 0;
width: 0;
height: 0;
}
.slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #ccc;
transition: .4s;
border-radius: 34px;
}
.slider:before {
position: absolute;
content: "";
height: 26px;
width: 26px;
left: 4px;
bottom: 4px;
background-color: white;
transition: .4s;
border-radius: 50%;
}
input:checked + .slider {
background-color: #2196F3;
}
input:checked + .slider:before {
transform: translateX(26px);
}
添加开关状态文本
在滑块上显示ON/OFF文字提示:

.slider:after {
content: 'OFF';
color: white;
position: absolute;
transform: translate(-50%, -50%);
top: 50%;
left: 70%;
font-size: 10px;
}
input:checked + .slider:after {
content: 'ON';
left: 30%;
}
方形开关样式修改
将圆角改为直角实现方形开关:
.square .slider {
border-radius: 0;
}
.square .slider:before {
border-radius: 0;
}
不同尺寸开关实现
通过修改基础尺寸创建不同大小的开关:
.switch.small {
width: 40px;
height: 22px;
}
.switch.small .slider:before {
height: 16px;
width: 16px;
}






