共计 778 个字符,预计需要花费 2 分钟才能阅读完成。
原理:首先把 input 元素隐藏掉,然后用 CSS 设置 label 元素(其他元素也可以)的样式,选中时的样式使用 input:check+label 选中 label,无须使用图片和 JS
效果预览
html 代码
<div class="radio"> | |
<input type="checkbox" id="sex1"> | |
<label for="sex1"></label> | |
男 | |
</div> | |
<div class="radio"> | |
<input type="checkbox" id="sex2"> | |
<label for="sex2"></label> 女 | |
</div> |
CSS 代码
.radio { | |
position: relative; | |
display: inline-block; | |
margin-right: 12px; | |
} | |
.radio input { | |
width: 15px; | |
height: 15px; | |
appearance: none;/* 清楚默认样式 */ | |
-webkit-appearance: none; | |
opacity: 0; | |
outline: none; | |
z-index: 8; /* 让 input 层级高于 label,使之能选中 */ | |
} | |
.radio label { | |
position: absolute; | |
left: 0; | |
top: 6px; | |
width: 15px; | |
height: 15px; | |
border: 1px solid #3582E9; | |
} | |
.radio input:checked+label::after { | |
content: ""; | |
position: absolute; | |
left: 4px; | |
top: 0px; | |
/* 这里显示矩形的一半边框再旋转 45 度来实现对勾样式 */ | |
width: 5px; | |
height: 12px; | |
border-right: 1px solid #000000; | |
border-bottom: 1px solid #000000; | |
transform: rotate(45deg); | |
} |
正文完