css开关按钮制作
使用纯CSS制作开关按钮
通过CSS的<input type="checkbox">和伪元素实现开关效果。利用:checked伪类捕获选中状态,结合::before或::after伪元素创建滑动开关的视觉样式。
<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);
}
添加动画效果的开关按钮
通过调整transition属性和阴影效果增强交互体验。使用box-shadow在激活状态时添加发光效果。

.slider {
box-shadow: 0 0 1px rgba(0,0,0,0.5);
}
input:checked + .slider {
box-shadow: 0 0 5px #2196F3;
}
input:focus + .slider {
box-shadow: 0 0 10px #2196F3;
}
不同形状的开关按钮
将border-radius改为0可创建方形开关,或通过自定义值实现圆角矩形。

/* 方形开关 */
.square .slider {
border-radius: 0;
}
.square .slider:before {
border-radius: 0;
}
禁用状态的样式处理
通过:disabled选择器为不可用状态添加灰度样式。
input:disabled + .slider {
background-color: #e0e0e0;
cursor: not-allowed;
}
input:disabled + .slider:before {
background-color: #f5f5f5;
}
响应式尺寸调整
使用em或rem单位使开关按钮能随字体大小缩放。
.responsive-switch {
width: 3.75em;
height: 2.125em;
}
.responsive-slider:before {
width: 1.625em;
height: 1.625em;
}






