在前端开发中,我们经常需要使用单选框。通过CSS,我们可以美化单选框的样式来提升用户体验。/ 去掉默认单选框样式 / input { appearance: none; mozappearance: ...
在前端开发中,我们经常需要使用单选框。通过CSS,我们可以美化单选框的样式来提升用户体验。
/* 去掉默认单选框样式 */
input[type=radio] {
appearance: none;
-moz-appearance: none;
-webkit-appearance: none;
border: none;
outline: none;
}
/* 添加自定义单选框样式 */
input[type=radio] + label:before {
content: '';
display: inline-block;
vertical-align: middle;
width: 20px;
height: 20px;
margin-right: 10px;
border: 2px solid #333;
border-radius: 50%;
}
/* 添加选中状态样式 */
input[type=radio]:checked + label:before {
background-color: #333;
}
/* 隐藏原始单选框,只显示自定义样式 */
input[type=radio] {
display: none;
}
input[type=radio] + label:before {
display: inline-block;
content: '';
width: 18px;
height: 18px;
border-radius: 50%;
border: 1px solid #aaa;
margin-right: 0.5em;
vertical-align: -6px;
}
input[type=radio]:checked + label:before {
background: #0078d7;
border-color: #0078d7;
color: white;
content: '\2022';
text-align: center;
line-height: 18px;
} 以上代码可以让我们自定义单选框的样式,并且添加选中状态样式。同时我们还可以通过隐藏原始单选框的方式,只显示自定义的样式。