都知道input type類型為 checkbox和radio的默認(rèn)樣式非常丑陋,并且在不同的平臺(tái)上顯示的效果不同,網(wǎng)上有很多自定義樣式的方法,但我認(rèn)為都比較麻煩,有的需要兩個(gè)標(biāo)簽,有的需要配合js.以下是我的方法,核心是:appearance,::after,::before
這是要實(shí)現(xiàn)的效果:
HTML代碼:
<div style="margin-top: .78rem">
<span class="choose">
<input class="icon-checked" type="radio" name="onsale" />營(yíng)業(yè)中
</span >
<span class="choose">
<input class="icon-checked" type="radio" name="onsale" />暫停營(yíng)業(yè)
</span>
</div>
CSS代碼
input.icon-checked {
position: relative;
width: .3rem; //顯示為20px,實(shí)際為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;
}
兼容性:
現(xiàn)代瀏覽器大部分支持或支持其替代屬性,IE9等CSS3未完全支持的瀏覽器兼容性有問(wèn)題
另外,
可以在content中寫(xiě)svg,就不需要設(shè)置字體圖標(biāo)了,更加純粹的純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>