CSS开关制作
CSS开关制作方法
通过纯CSS实现开关效果,无需JavaScript,利用<input type="checkbox">和CSS选择器实现交互样式切换。
基础HTML结构
<label class="switch">
<input type="checkbox">
<span class="slider"></span>
</label>
核心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;
}
方形开关变体
修改圆角值为0即可:

.slider.square {
border-radius: 0;
}
.slider.square:before {
border-radius: 0;
}
动画增强
添加缩放效果提升交互感:
input:focus + .slider {
box-shadow: 0 0 1px #2196F3;
}
.slider:active:before {
transform: scale(1.1);
}
尺寸调整技巧
通过修改根元素尺寸实现整体缩放:
.switch.small {
width: 40px;
height: 20px;
}
.switch.small .slider:before {
width: 16px;
height: 16px;
}





