这种纯CSS3美化单选按钮radio的方法适用于如下状况:字体
一、可兼容IE9以上,须要兼容IE8的要写IE的hack把样式去掉spa
二、只支持单选按钮radio,由于单选按钮选中样式的圆圈能够用CSS作出来,可是复选按钮checkbox的选中效果对勾就须要图片或者图标字体库code
三、不须要JS支持切换效果orm
下图是最终效果图:blog
HTML代码:图片
<label for="man" class="radio"> <span class="radio-bg"></span> <input type="radio" name="sex" id="man" value="男" checked="checked" /> 男 <span class="radio-on"></span> </label> <label for="woman" class="radio"> <span class="radio-bg"></span> <input type="radio" name="sex" id="woman" value="女" /> 女 <span class="radio-on"></span> </label>
CSS代码:input
.radio{ display: inline-block; position: relative; line-height: 18px; margin-right: 10px; cursor: pointer; } .radio input{ display: none; } .radio .radio-bg{ display: inline-block; height: 18px; width: 18px; margin-right: 5px; padding: 0; background-color: #45bcb8; border-radius: 100%; vertical-align: top; box-shadow: 0 1px 15px rgba(0, 0, 0, 0.1) inset, 0 1px 4px rgba(0, 0, 0, 0.1) inset, 1px -1px 2px rgba(0, 0, 0, 0.1); cursor: pointer; transition: all 0.2s ease; } .radio .radio-on{ display: none; } .radio input:checked + span.radio-on{ width: 10px; height: 10px; position: absolute; border-radius: 100%; background: #FFFFFF; top: 4px; left: 4px; box-shadow: 0 2px 5px 1px rgba(0, 0, 0, 0.3), 0 0 1px rgba(255, 255, 255, 0.4) inset; background-image: linear-gradient(#ffffff 0, #e7e7e7 100%); transform: scale(0, 0); transition: all 0.2s ease; transform: scale(1, 1); display: inline-block; }
这个方法中最重要的是选中效果的类名:.radio input:checked + span.radio-onit
+是CSS2的伪类,其意义为:div+p 选择紧接在 <div> 元素以后的全部 <p> 元素。io
也就是找到选中的(:checked)的input,其以后的类名为radio-on的span元素作选中圆圈效果。form
网上有不少美化方法是把label作成了圆圈,可是这样的话,单选的文字就必需要要放到label的外面,这致使了点击文字的时候,不能切换单选效果。
因此我在label里加了一个类名为radio-bg的span来专门作后面大的圆圈,再用一个类名为radio-on的span来作选中的前面小的圆圈。
这样就保留了点击label里的文字,也能够切换单选的效果。