CheckBox 美化方法
使用 CSS 自定义 CheckBox 样式的几种方案
问题
原生 CheckBox 样式简陋且各浏览器表现不一致,如何美化 CheckBox?
解答
方案一:隐藏原生 + 伪元素(推荐)
<label class="checkbox">
<input type="checkbox" />
<span class="checkmark"></span>
选项文本
</label>
.checkbox {
display: inline-flex;
align-items: center;
cursor: pointer;
user-select: none;
}
/* 隐藏原生 checkbox */
.checkbox input {
position: absolute;
opacity: 0;
width: 0;
height: 0;
}
/* 自定义外框 */
.checkmark {
width: 18px;
height: 18px;
border: 2px solid #ccc;
border-radius: 4px;
margin-right: 8px;
position: relative;
transition: all 0.2s;
}
/* 选中时的勾 */
.checkmark::after {
content: '';
position: absolute;
display: none;
left: 5px;
top: 1px;
width: 5px;
height: 10px;
border: solid #fff;
border-width: 0 2px 2px 0;
transform: rotate(45deg);
}
/* 选中状态 */
.checkbox input:checked + .checkmark {
background: #2196f3;
border-color: #2196f3;
}
.checkbox input:checked + .checkmark::after {
display: block;
}
/* hover 效果 */
.checkbox:hover .checkmark {
border-color: #2196f3;
}
方案二:appearance + 伪元素
input[type="checkbox"] {
appearance: none;
-webkit-appearance: none;
width: 18px;
height: 18px;
border: 2px solid #ccc;
border-radius: 4px;
cursor: pointer;
position: relative;
}
input[type="checkbox"]:checked {
background: #2196f3;
border-color: #2196f3;
}
/* 勾选标记 */
input[type="checkbox"]:checked::after {
content: '';
position: absolute;
left: 5px;
top: 1px;
width: 5px;
height: 10px;
border: solid #fff;
border-width: 0 2px 2px 0;
transform: rotate(45deg);
}
方案三:accent-color(最简单)
/* 现代浏览器支持,一行搞定主题色 */
input[type="checkbox"] {
accent-color: #2196f3;
width: 18px;
height: 18px;
}
关键点
- 方案一兼容性最好,通过隐藏原生 input,用 label 关联实现点击
- 方案二使用
appearance: none移除默认样式,代码更简洁 - 方案三
accent-color是 CSS4 新属性,最简单但自定义程度有限 - 隐藏 input 用
opacity: 0而非display: none,保留键盘可访问性 - 勾选标记用边框旋转 45° 实现,比引入图标更轻量
目录