一、CSS单选框标签
单选框在HTML中是通过input标签来实现的,type属性值为radio。
<input type="radio" name="gender" value="male"> Male
<input type="radio" name="gender" value="female"> Female
其中,name属性值相同的单选框会被视为一组,value属性值对应的是被选中时提交的数据。
二、CSS单选框外观
1. CSS单选框方框
单选框默认外观为圆形,但可以通过CSS将其改为方框:
input[type="radio"] {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
width: 20px;
height: 20px;
border: 1px solid #ccc;
border-radius: 0;
}
2. CSS单选框颜色
单选框的颜色可以通过设置背景色和选中时的伪类(:checked)来实现:
input[type="radio"] {
background-color: #f0f0f0;
}
input[type="radio"]:checked {
background-color: #00cc99;
}
3. CSS单选框打钩
单选框默认为实心圆,可以使用伪类(:before)将其改为打钩:
input[type="radio"]:checked:before {
content: '\2713';
text-align: center;
width: 20px;
height: 20px;
border-radius: 50%;
background-color: #00cc99;
color: #fff;
}
三、CSS单选框优化
1. CSS单选框纵着排列
默认情况下,单选框是横向排列的,可以通过设置display属性来控制:
input[type="radio"] {
display: block;
margin-bottom: 10px;
}
2. CSS单选框变成方框
在改为方框时,由于原来的圆形和打钩都会被保留下来,可以通过设置一个额外的div来解决这个问题:
<div class="radio-item">
<input type="radio" name="gender" value="male"> Male
</div>
<div class="radio-item">
<input type="radio" name="gender" value="female"> Female
</div>
.radio-item {
display: inline-block;
margin-right: 10px;
position: relative;
}
.radio-item input[type="radio"] {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
width: 20px;
height: 20px;
border: 2px solid #ccc;
border-radius: 0;
position: absolute;
top: 0;
left: 0;
}
.radio-item input[type="radio"]:checked:before {
content: '';
display: inline-block;
width: 10px;
height: 10px;
background-color: #00cc99;
position: absolute;
top: 5px;
left: 5px;
}
3. CSS单选框为矩形
如果需要将单选框变成矩形,则需要调整宽度和高度,同时调整圆角:
input[type="radio"] {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
width: 20px;
height: 12px;
border: 1px solid #ccc;
border-radius: 6px;
}
input[type="radio"]:checked:before {
content: '';
display: inline-block;
width: 10px;
height: 10px;
background-color: #00cc99;
border-radius: 50%;
position: absolute;
top: 1px;
left: 5px;
}
四、CSS多选框
多选框使用input标签,type属性值为checkbox,在CSS上和单选框类似。只需要注意name属性值不同即可将多个多选框分组。
参考资料
1. https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/radio
2. https://www.w3schools.com/css/tryit.asp?filename=trycss_forms_radio
3. https://stackoverflow.com/questions/44940944/how-to-style-radio-button-with-a-border-radius
原创文章,作者:UGKQ,如若转载,请注明出处:https://www.506064.com/n/135924.html
微信扫一扫
支付宝扫一扫