css切换按钮制作
基础样式切换按钮
使用CSS和HTML创建一个简单的切换按钮,通过复选框隐藏实现状态切换:
<label class="switch">
<input type="checkbox">
<span class="slider"></span>
</label>
.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);
}
动画增强效果
为切换按钮添加更丰富的动画效果:
.slider {
box-shadow: 0 0 1px #2196F3;
}
input:focus + .slider {
box-shadow: 0 0 5px #2196F3;
}
.slider:after {
content: "OFF";
color: white;
display: block;
position: absolute;
transform: translate(-50%, -50%);
top: 50%;
left: 70%;
font-size: 10px;
}
input:checked + .slider:after {
content: "ON";
left: 30%;
}
不同风格变体
创建扁平化风格的切换按钮:
.slider.flat {
border-radius: 0;
}
.slider.flat:before {
border-radius: 0;
}
iOS风格的切换按钮:
.slider.ios {
background-color: #4CD964;
}
.slider.ios:before {
background-color: white;
box-shadow: 0 2px 5px rgba(0,0,0,0.2);
}
使用伪类实现纯CSS切换
不使用JavaScript实现状态切换:

<label class="pure-switch">
<input type="checkbox">
<div class="switch-wrapper">
<div class="switch-bg"></div>
<div class="switch-thumb"></div>
</div>
</label>
.pure-switch input {
position: absolute;
opacity: 0;
}
.switch-wrapper {
position: relative;
width: 50px;
height: 24px;
}
.switch-bg {
position: absolute;
width: 100%;
height: 100%;
background: #e5e5e5;
border-radius: 12px;
transition: background 0.2s;
}
.switch-thumb {
position: absolute;
top: 2px;
left: 2px;
width: 20px;
height: 20px;
background: white;
border-radius: 50%;
box-shadow: 0 1px 3px rgba(0,0,0,0.4);
transition: transform 0.2s;
}
input:checked ~ .switch-wrapper .switch-bg {
background: #4CD964;
}
input:checked ~ .switch-wrapper .switch-thumb {
transform: translateX(26px);
}






