css3实现单选、多选按钮改变其原生样式用图片代替

最近才开始写博客,所以把前几个月做项目时遇到的问题整理一下写出来,众所周知,表单中的一写元素原生样式不是很好看,项目中用到的时候需要优化,今天我就写一下单选按钮很多选按钮的样式的优化,首先自己要做出按钮选中之前的图片和按钮选中之后的图片。然后就是代码了。直接上代码:(代码比较多,这是我之前在做项目时样式都搬过来了,样式什么都是可以自己写的。)

HTML代码结构如下:


1
<div class="radio" > 2 <label> 3 <input type="radio" name="sex" value="" /> 4 <div class="option"></div><!--该div盛放的是优化后的按钮图片--> 5 <span class="opt-text"></span> 6 </label> 7 </div> 8 <div class="radio"> 9 <label> 10 <input type="radio" name="sex" value="" /> 11 <div class="option"></div><!--该div盛放的是优化后的按钮图片--> 12 <span class="opt-text"></span> 13 </label> 14 </div>
css代码如下:

1 label
{ /*设置label的样式*/ 2 width: 100%; 3 padding: 10px 0px; 4 display: block; 5 line-height: 20px; 6 position: relative; 7 font-weight: normal; 8 } 9 .radio .option { /*把优化后的按钮图片设置为该div的背景图片,把该div定位到原生样式的上方,遮盖住原生样式。*/ 10 width: 25px; 11 height: 25px; 12 position: absolute; 13 top: 10px; 14 left: 0px; 15 background-size: cover; 16 background: url(img/radio.png) no-repeat; 17 background-size: cover; 18 } 19 .radio input[type="radio"] { /*为了保险起见,把原生样式隐藏掉*/ 20 display: inline-block ; 21 margin-right: 15px ; 22 opacity: 0 ; 23 } 24 input[type="radio"]:checked+div { /*当radiuo被选中时,把input下边的div标签的背景图片替换掉*/ 25 background: url(img/radio-checked.png) no-repeat; 26 background-size: cover; 27 }

最后贴上一张效果图:

原文地址:https://www.cnblogs.com/lxgandlz/p/5087844.html