CSS制作checkbox开关
CSS制作checkbox开关的方法
通过CSS可以自定义checkbox的样式,将其转换为开关效果。以下是几种常见的实现方式:
基础开关样式
使用label和checkbox结合,隐藏原生checkbox,通过label模拟开关:
<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.round {
border-radius: 34px;
}
.slider.round:before {
border-radius: 50%;
}
方形开关样式
修改为方形开关:
.slider {
border-radius: 0;
}
.slider:before {
border-radius: 0;
}
添加文字提示
在开关上添加ON/OFF文字:

.slider:after {
content: "OFF";
color: white;
display: block;
position: absolute;
transform: translate(-50%, -50%);
top: 50%;
left: 70%;
font-size: 10px;
font-family: Verdana, sans-serif;
}
input:checked + .slider:after {
content: "ON";
left: 30%;
}
不同尺寸开关
通过调整尺寸参数创建不同大小的开关:
.small-switch {
width: 40px;
height: 20px;
}
.small-switch .slider:before {
width: 16px;
height: 16px;
}
.large-switch {
width: 80px;
height: 40px;
}
.large-switch .slider:before {
width: 36px;
height: 36px;
}
禁用状态样式
为开关添加禁用状态样式:
input:disabled + .slider {
opacity: 0.5;
cursor: not-allowed;
}
这些方法提供了灵活的自定义checkbox开关方案,可以根据需求调整颜色、尺寸、形状等参数。通过CSS过渡效果可以实现平滑的开关动画,提升用户体验。






