css制作开关按钮
CSS 制作开关按钮
开关按钮(Toggle Switch)是一种常见的 UI 元素,用于切换状态(如开启/关闭)。以下是几种实现方式:
纯 CSS 开关按钮
使用 HTML 的 <input type="checkbox"> 和 CSS 伪元素实现:

<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);
}
圆角矩形开关按钮
修改 border-radius 可以改变按钮样式:
.slider {
border-radius: 8px;
}
.slider:before {
border-radius: 5px;
}
添加文字提示
在按钮上显示 ON/OFF 文字:

.slider:after {
content: "OFF";
color: white;
display: block;
position: absolute;
transform: translateX(10px);
}
input:checked + .slider:after {
content: "ON";
transform: translateX(-10px);
}
不同尺寸调整
通过修改基础尺寸变量控制大小:
:root {
--switch-width: 80px;
--switch-height: 40px;
--slider-size: 32px;
}
.switch {
width: var(--switch-width);
height: var(--switch-height);
}
.slider:before {
height: var(--slider-size);
width: var(--slider-size);
}
禁用状态样式
为禁用状态添加特殊样式:
input:disabled + .slider {
opacity: 0.5;
cursor: not-allowed;
}
这些方法提供了灵活的开关按钮实现方案,可根据具体需求调整颜色、尺寸和交互效果。






