单选按钮 / 复选框 样式自定义
一直以来都对单选按钮(radio) / 复选框(checkbox) 的默认样式感到头疼,不够美观!
恰好学习css3 学到了一个选择器 :checked,学着做了一个简单的样式自定义。
主要的思想在于:设置自带的样式的透明度为0,然后使用绝对定位混淆视听
先来说说单选按钮
代码如下:
css:
1 <style type="text/css"> 2 *{ 3 padding: 0; 4 margin: 0; 5 } 6 .content{ 7 border: 1px solid black; 8 width: 450px; 9 height: 200px; 10 margin:0 auto; 11 margin-top: 100px; 12 } 13 .sex{ 14 margin-left: 35%; 15 margin-top: 15%; 16 } 17 .radio_btn{ 18 background: orange; 19 display: inline-block; 20 width: 30px; 21 height: 30px; 22 border-radius: 30px; 23 position: relative; 24 vertical-align: middle; 25 } 26 .radio_btn input{ 27 width: 100%; 28 height: 100%; 29 position: absolute; 30 top: 0; 31 left: 0; 32 z-index: 100; 33 opacity: 0; 34 } 35 .radio_btn span{ 36 background: #fff; 37 width: 10px; 38 height: 10px; 39 display: inline-block; 40 position: absolute; 41 z-index: 1; 42 top: 10px; 43 left: 10px; 44 border-radius: 10px; 45 } 46 .radio_btn input[type="radio"] + span{ 47 opacity: 0; 48 } 49 .radio_btn input[type="radio"]:checked + span{ 50 opacity: 1; 51 } 52 </style>
html:
1 <div class="content"> 2 <div class="sex"> 3 4 <span class="radio_btn"> 5 <input type="radio" name="sex" id="man" /> 6 <span></span> 7 </span> 8 <label for="man" >男</label> 9 10 <span class="radio_btn"> 11 <input type="radio" name="sex" id="male"> 12 <span></span> 13 </span> 14 <label for="male">女</label> 15 16 </div> 17 </div>
结果如下:
图1-1
相对于默认样式,是不是看起来舒服多了?下面我们看看复选框
css:
<div class="check-box"> <div class="wrapper"> <div class="box"> <input type="checkbox" checked="checked" id="milk" /><span>√</span> </div> <lable for="milk">牛奶</lable> </div> <div class="wrapper"> <div class="box"> <input type="checkbox" id="water" /><span>√</span> </div> <label for="water">水</label> </div> </div>
html:
<style type="text/css"> .check-box { border: 1px solid #ccc; padding: 20px; width: 300px; margin: 30px auto; } .wrapper { margin-bottom: 10px; } .box { display: inline-block; width: 20px; height: 20px; margin-right: 10px; position: relative; border: 2px solid orange; vertical-align: middle; } .box input { opacity: 0; position: absolute; height: 20px; width: 20px; top:-3px; left:-3px; z-index: 100; cursor: pointer; } .box span { position: absolute; top: -10px; right: 3px; font-size: 30px; font-weight: bold; font-family: Arial; -webkit-transform: rotate(30deg); transform: rotate(30deg); color: orange; z-index: 2; } input[type="checkbox"] + span { opacity: 0; } input[type="checkbox"]:checked + span { opacity: 1; } </style>
结果如下:
√
牛奶
√
图1-2
以上内容,如有错误请指出,不甚感激。