元素的初始样式都不怎么好看,我们一般修改样式会想到直接在那元素上添加样式,比如background、border等,在大多数元素上是可以这么做,但当遇上了单选框会毫无反应。
例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>style无法直接修改单选框样式</title>
<style>
.radio{
width: 100px;
height: 100px;
background-color: red;
}
</style>
</head>
<body>
<input type="radio" class="radio"/>
</body>
</html>
怎么解决呢?
使用label进行伪元素(或一些标签,比如i,em,span等)和input绑定,隐藏单选框,显示伪元素,且使用css选择器:checked进行点击后伪元素(或绑定标签)内容(或样式)的修改。
以下例子只是修改伪元素的内容。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>修改单选框样式</title>
<style>
/*.radio{*/
/*width: 100px;*/
/*height: 100px;*/
/*background-color: red;*/
/*}*/
.radio {
display: none;
}
/* +代表相邻的元素 */
.radio + i {
font-style: normal;
text-align: center;
font-size: 16px;
}
/* ::after伪元素,使用伪元素,必须含有content属性,可以为'',但不可不写 */
.radio + i::after {
content: '☆';
}
/* 点击后伪元素内容变化 */
.radio:checked + i::after {
content: '★';
}
</style>
</head>
<body>
<label>
<input type="radio" class="radio" name="aa" id="aa"/>
<i></i>
aa
</label>
<label>
<input type="radio" class="radio" name="aa" id="bb"/>
<i></i>
bb
</label>
</body>
</html>
完成后的结果: