css开关按钮制作
基本HTML结构
创建一个简单的开关按钮需要HTML和CSS配合。HTML部分通常使用<label>和<input type="checkbox">实现交互逻辑。
<label class="switch">
<input type="checkbox">
<span class="slider"></span>
</label>
基础CSS样式
通过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);
}
添加禁用状态
通过:disabled选择器为不可用状态添加样式。
input:disabled + .slider {
opacity: 0.5;
cursor: not-allowed;
}
方形开关变体
将圆角改为直角即可实现方形开关。
.square .slider {
border-radius: 0;
}
.square .slider:before {
border-radius: 0;
}
小尺寸开关
通过调整尺寸参数实现更小的开关。
.small-switch {
width: 40px;
height: 22px;
}
.small-switch .slider:before {
height: 16px;
width: 16px;
}
.small-switch input:checked + .slider:before {
transform: translateX(18px);
}
动画效果增强
添加缩放动画使交互更生动。
.slider:active:before {
transform: scale(1.2);
}
input:checked + .slider:active:before {
transform: translateX(26px) scale(1.2);
}
自定义颜色方案
通过CSS变量实现主题色快速更换。
:root {
--switch-on: #4CAF50;
--switch-off: #f44336;
}
.custom .slider {
background-color: var(--switch-off);
}
.custom input:checked + .slider {
background-color: var(--switch-on);
}
图标开关
在滑块上添加图标指示状态。

.icon-switch .slider:after {
content: "✖";
position: absolute;
right: 8px;
top: 3px;
color: white;
}
.icon-switch input:checked + .slider:after {
content: "✓";
left: 8px;
right: auto;
}






