【前言】
本文简单介绍一种优化自定义单选和多选框样式的方法
【主体】
原理:(1)利用label关联标签进行模拟,然后将原选择的按钮隐藏;
(2)选中样式设置:input[type="radio"]:checked+label和input[type="checkbox"]:checked+label
(3)利用伪元素添加选中后的√和圆点--content内填入css特殊字符表
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>优化单选多选</title>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
hr{
margin: 20px 0;
}
input[type="radio"],input[type="checkbox"]{
vertical-align: middle;
margin: 0 3px;
}
/*label模拟*/
.checkbox_area label{
display: inline-block;
background: white;
width: 20px;
height: 20px;
vertical-align: text-top;
border:1px solid #d3d3d3;
}
.radio_area label{
box-sizing: border-box;
display: inline-block;
background: white;
width: 20px;
height: 20px;
border: 1px solid gray;
border-radius: 50%;
vertical-align: middle;
}
/*隐藏自带单选多选框*/
.checkbox_area input[type="checkbox"],.radio_area input[type="radio"]{
display: none;
}
/*鼠标悬停时样式*/
.checkbox_area label:hover,.radio_area label:hover{
cursor: pointer;
}
/*多选框选中样式*/
.checkbox_area input[type="checkbox"]:checked+label{
text-align: center;
background: #2783FB;
line-height: 20px;
}
.checkbox_area input[type="checkbox"]:checked+label:after{
content: "\2714";
color: white;
}
/*单选框选中样式*/
.radio_area input[type="radio"]:checked+label{
font-size: 30px;
background: #2783FB;
text-align: center;
line-height: 15px;
}
.radio_area input[type="radio"]:checked+label:after{
content: "\2022";
color: white;
}
.method1{
width: 600px;
height: 300px;
margin: 10px auto;
border:1px solid red;
}
.method1 p{
margin: 10px 0;
}
</style>
</head>
<body>
<div class="method1">
<h3 style="font-size: 15px;font-weight: 100;line-height: 25px;text-indent:2em">
原理:(1)利用label关联标签进行模拟,然后将原选择的按钮隐藏;
(2)选中样式设置:input[type="radio"]:checked+label和input[type="checkbox"]:checked+label
(3)利用伪元素添加选中后的√和圆点--content内填入css特殊字符表
</h3>
<div class="checkbox_area">
<p>(复选框)科目:</p>
语文<input id="chinese" type="checkbox" name="list"><label for="chinese"></label>
数学<input id="math" type="checkbox" name="list"><label for="math"></label>
英语<input id="engilsh" type="checkbox" name="list"><label for="engilsh"></label>
</div>
<hr>
<div class="radio_area">
<p>(单选框)性别:</p>
男<input id="man" type="radio" name="sex"><label for="man"></label>
女<input id="woman" type="radio" name="sex"><label for="woman"></label>
</div>
</div>
</body>
</html>