都知道input type类型为 checkbox和radio的默认样式非常丑陋,并且在不同的平台上显示的效果不同,网上有很多自定义样式的方法,但我认为都比较麻烦,有的需要两个标签,有的需要配合js.以下是我的方法,核心是:appearance,::after,::before
这是要实现的效果:
HTML代码:
<div style="margin-top: .78rem">
<span class="choose">
<input class="icon-checked" type="radio" name="onsale" />营业中
</span >
<span class="choose">
<input class="icon-checked" type="radio" name="onsale" />暂停营业
</span>
</div>
CSS代码
input.icon-checked {
position: relative;
width: .3rem; //显示为20px,实际为30px,方便触摸
height: .3rem;
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
}
input.icon-checked:after {
display: inline-block;
width: .2rem;
height: .2rem;
content: '';
vertical-align: middle;
border: 3px solid #b4b4b4;
}
input.icon-checked:checked:before {
font-size: 32px;
position: absolute;
top: -.08rem;
left: -.05rem;
content: '\e613';
color: #d11d1d;
}
兼容性:
现代浏览器大部分支持或支持其替代属性,IE9等CSS3未完全支持的浏览器兼容性有问题
另外,
可以在content中写svg,就不需要设置字体图标了,更加纯粹的纯css,如:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<style>
#square{
background-color: green;
width: 100px;
height: 100px;
}
#square:before{
display: block;
content: url("data:image/svg+xml;charset=UTF-8, <svg xmlns='http://www.w3.org/2000/svg' version='1.1' height='100' width='100'><circle cx='50' cy='50' r='40' stroke='black' stroke-width='3' fill='red' /></svg>");
background-size: 28px 28px;
height: 28px;
width: 28px;
}
</style>
<title>Document</title>
</head>
<body>
<div id="square"></div>
</body>
</html>