纯CSS方法美化一个单选按钮/复选框
看见了吧,前面那个小单选按钮,UI 小姐姐画的还是很好看的,看看我们前端用到了什么技术。
很明显这个小东西是使用 HTML 原生的 radio 和 CheckBox 来实现的,原生的单选按钮/复选框样式如下:
原生单选按钮和复选框
写项目的时候看了看 element-ui 和 View UI(十月份之前还叫 iview 来,改名了。。。)都没有直接组件可以拿来就用。那没办法了可以借助插件 pretty checkbox 来实现。
A pure CSS library to beautify checkbox and radio buttons
这个插件好呀,插件效果是茫茫的多,但是为了个小功能就用个插件有点杀鸡焉用牛刀的感觉,算了,还是自己来吧。不就写点 css 吗。 come on 反正年底了,划划水了,走起。
看下实现效果:
纯CSS方法美化一个单选按钮/复选框
源代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 | <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>纯CSS方法美化一个单选按钮/复选框</title> <style> body{ margin: 100px 100px; } .checkbox:checked { background:#E29F00; } .checkbox { outline: none; width:20px; height:20px; background-color:#ffffff; border:solid 1px #dddddd; -webkit-border-radius:50%; border-radius:50%; font-size:0.8rem; margin:0; padding:0; position:relative; display:inline-block; vertical-align:top; cursor:default; -webkit-appearance:none; -webkit-user-select:none; user-select:none; -webkit-transition:background-color ease 0.1s; transition:background-color ease 0.1s; } .checkbox:checked::after { content:''; top:3px; left:3px; position:absolute; background:transparent; border:#fff solid 2px; border-top:none; border-right:none; height:6px; width:10px; -moz-transform:rotate(-45deg); -ms-transform:rotate(-45deg); -webkit-transform:rotate(-45deg); transform:rotate(-45deg); } </style> </head> <body> <input type="checkbox" class="checkbox"> </body> </html> |
实现思路:
- 第一比较重要的 CSS 属性 appearance ,但是所有主流浏览器都不支持 appearance 属性,使用的时候必须加前缀。Firefox 支持替代的 -moz-appearance 属性,Safari 和 Chrome 支持替代的 -webkit-appearance 属性。其主要作用是去除系统默认的样式,常用于 IOS 下移除原生样式,用在复选框上,复选框直接消失,这时复选框的样式就能重写了。
做个试验,页面放置一个复选框:
1 | <input type="checkbox" class="box"> |
给复选框添加
这时候设置以下样式我们就能得到个圆:
1 2 3 4 5 6 7 | .box{ -webkit-appearance: none; width: 30px; height: 30px; border-radius: 50%; border: 2px solid red; } |
但此时这个东西有个缺点,看动图演示:
动图演示
我们去点击会默认出现外边框,圆外区域点击下才能消失,这个很好理解,input 为 text 的时候,失焦聚焦的效果而且。checkbox 说到底也是 input 所以也会有这个效果,只要我们在加上一条 css 语句就行了。
1 | outline: none;//去除默认外边框 |
这时候就差一个背景变色和对号显示了