css小技巧:单选框和复选框的样式
单选框和复选框的样式
让我们一起不使用图片来设置复选框的样式:
<!-- html -->
<input type="checkbox" id="check" name="check" />
<label for="check">Checkbox</label>
复制代码
<!-- css -->
input[type=checkbox] {display: none;}
input[type=checkbox] + label:before {
content: "";
border: 1px solid #000;
font-size: 11px;
line-height: 10px;
margin: 0 5px 0 0;
height: 10px;
width: 10px;
text-align: center;
vertical-align: middle;
}
input[type=checkbox]:checked + label:before {
content: "\2713";
}
复制代码
正如你所看见的,我们隐藏了原有的复选框,改为使用伪元素和伪类:checked
(IE9+)来表现它。当它被选中时,一个设置在content
里的Unicode编码的字符将会显示出来。
值得注意的是,Unicode编码在CSS和HTML中的写法是不一样的。在CSS中它是一个以反斜杠为开始的十六进制数,而在HTML中它是十进制的,比如
✓
。 接着为我们的复选框添加一些动画效果:
<!-- checkbox -->
input[type=checkbox] + label:before {
content: "\2713";
color: transparent;
transition: color ease .3s;
}
input[type=checkbox]:checked + label:before {
color: #000;
}
<!-- radio -->
input[type=radio] + label:before {
content: "\26AB";
border: 1px solid #000;
border-radius: 50%;
font-size: 0;
transition: font-size ease .3s;
}
input[type=radio]:checked + label:before {
font-size: 10px;
}
复制代码

作者:Jrain
THE END