如何修改HTML默认复选框样式:选中时显示小白色方块?
自定义复选框样式解决方案
直接调整你的代码,通过伪元素实现需求的样式效果:
完整代码
CSS 代码
/* 容器设置相对定位,确保内部元素对齐 */ .checkbox-container { position: relative; padding-left: 25px; cursor: pointer; display: inline-flex; align-items: center; } /* 隐藏原生复选框 */ .checkbox-container input[type="checkbox"] { position: absolute; opacity: 0; cursor: pointer; } /* 未选中状态的自定义复选框 */ .checkmark { position: absolute; top: 50%; left: 0; transform: translateY(-50%); width: 15px; height: 15px; background-color: black; border: 1px solid white; } /* 选中状态保持黑色背景 */ .checkbox-container input[type="checkbox"]:checked + .checkmark { background-color: black; } /* 用伪元素实现选中时的白色小方块 */ .checkbox-container input[type="checkbox"]:checked + .checkmark::after { content: ""; position: absolute; left: 3px; top: 3px; width: 9px; height: 9px; background-color: white; }
HTML 代码
<label class="checkbox-container"> <input type="checkbox"> <span class="checkmark"></span> Checkbox </label>
关键修改说明
- 给
.checkbox-container添加相对定位和内边距,避免复选框与文字重叠,同时让元素垂直对齐 - 修正未选中状态的
.checkmark样式,直接设置黑色背景+白色边框,匹配需求 - 通过
::after伪元素生成选中时的白色小方块,替代原生对勾,通过定位和尺寸调整实现居中效果
内容的提问来源于stack exchange,提问作者Divyanshu Rawat
相关产品推荐
相关产品推荐

