制作css开关
使用纯CSS创建开关
HTML结构需要一个<input type="checkbox">和对应的<label>元素,通过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);
}
添加动画效果的开关
通过调整过渡属性和阴影效果增强交互体验:

.slider {
box-shadow: 0 2px 5px rgba(0,0,0,0.2);
}
input:focus + .slider {
box-shadow: 0 0 1px #2196F3;
}
.slider:before {
box-shadow: 0 2px 5px rgba(0,0,0,0.2);
}
不同风格的开关样式
方形开关只需移除边框半径:
.slider.square {
border-radius: 0;
}
.slider.square:before {
border-radius: 0;
}
带图标的开关可在滑块前后添加内容:

.slider.icon:after {
content: "ON";
color: white;
position: absolute;
right: 10px;
top: 50%;
transform: translateY(-50%);
font-size: 10px;
}
.slider.icon:before {
content: "OFF";
color: #888;
left: 10px;
}
响应式开关设计
使用CSS变量和相对单位实现尺寸自适应:
.switch {
--switch-height: 1.5em;
--switch-width: calc(var(--switch-height) * 1.8);
width: var(--switch-width);
height: var(--switch-height);
}
.slider:before {
height: calc(var(--switch-height) - 0.4em);
width: calc(var(--switch-height) - 0.4em);
}
无障碍优化
添加屏幕阅读器支持:
<label class="switch">
<input type="checkbox" role="switch" aria-checked="false">
<span class="slider"></span>
<span class="visually-hidden">Toggle dark mode</span>
</label>
.visually-hidden {
position: absolute;
width: 1px;
height: 1px;
padding: 0;
margin: -1px;
overflow: hidden;
clip: rect(0,0,0,0);
white-space: nowrap;
border: 0;
}