css制作开关按钮
使用纯CSS制作开关按钮
通过CSS可以创建自定义样式的开关按钮,无需依赖JavaScript或图片。以下是几种常见的实现方式:
HTML结构
基础HTML结构通常使用<label>和<input type="checkbox">组合:
<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 {
border-radius: 0;
}
.slider:before {
border-radius: 0;
}
添加文字内容
在滑块上显示ON/OFF文字:
.slider:after {
content: "OFF";
color: white;
position: absolute;
right: 10px;
top: 50%;
transform: translateY(-50%);
}
input:checked + .slider:after {
content: "ON";
left: 10px;
right: auto;
}
禁用状态样式
添加禁用状态的视觉效果:
input:disabled + .slider {
opacity: 0.5;
cursor: not-allowed;
}
尺寸调整
通过修改基础尺寸变量可调整开关大小:
.switch {
--width: 60px;
--height: 34px;
--slider-size: 26px;
width: var(--width);
height: var(--height);
}
.slider:before {
width: var(--slider-size);
height: var(--slider-size);
}
动画效果增强
添加弹性动画效果:

input:checked + .slider:before {
transform: translateX(26px);
animation: bounce 0.3s ease-in-out;
}
@keyframes bounce {
0%, 100% { transform: translateX(26px); }
50% { transform: translateX(30px); }
}
这些方法提供了灵活的开关按钮实现方案,可根据项目需求调整颜色、尺寸和动画效果。






