用CSS3美化单选框 radio 、多选框 checkbox 和 switch开关按钮

4,477 阅读2分钟
原文链接: www.css88.com

用CSS3美化单选框 radio 、多选框 checkbox 和 switch开关按钮

发表于 by 愚人码头 被浏览 1,584 次 分享到:

小编推荐:掘金是一个高质量的技术社区,从 ECMAScript 6 到 Vue.js,性能优化到开源类库,让你不错过前端开发的每一个技术干货。各大应用市场搜索「掘金」即可下载APP,技术干货尽在掌握..

很多时候我们需要美化单选框 radio 和多选框 checkbox ,因为原生的样式比较丑陋,而且表现不统一。CSS3之前一般用 js 来模拟,而如今完全可以用纯CSS实现radio和checkbox的美化。对于移动端很早就写过相关的模拟样式:一个适合移动端的checkboxcss3实现的switch开关按钮 。这两篇文章仅仅支持移动端的页面,而 webkit 上也正好支持单标记的 input 元素是使用伪类(:before:after)。最近做PC端项目,考虑到兼容更多的PC浏览器,所以在这基础上作了一些改进。

先来看看效果:

再来看一下HTML结构:

<label class="bui-radios-label bui-radios-anim">
    <input type="radio" name="sex"/><i class="bui-radios"></i> 男
</label>

这个结构有一个 label 标签,其中包含 input 元素和 i 元素。基本的原理是:首先使用 visibility: hidden; opacity: 0;input 元素 “隐藏” 起来,利用 label 标签的特性,在点击时将 input 元素选中或取消选中。 i 元素结合伪类(:before:after)模拟单选框 radio 和多选框 checkbox 的外观。

最后看看CSS代码:

/* radio */
label.bui-radios-label input {
  position: absolute;
  opacity: 0;
  visibility: hidden;
}
 
label.bui-radios-label .bui-radios {
  display: inline-block;
  position: relative;
  width: 13px;
  height: 13px;
  background: #FFFFFF;
  border: 1px solid #979797;
  border-radius: 50%;
  vertical-align: -2px;
}
 
label.bui-radios-label input:checked + .bui-radios:after {
  position: absolute;
  content: "";
  width: 7px;
  height: 7px;
  background-color: #fff;
  border-radius: 50%;
  top: 3px;
  left: 3px;
}
 
label.bui-radios-label input:checked + .bui-radios {
  background: #00B066;
  border: 1px solid #00B066;
}
 
label.bui-radios-label input:disabled + .bui-radios {
  background-color: #e8e8e8;
  border: solid 1px #979797;
}
 
label.bui-radios-label input:disabled:checked + .bui-radios:after {
  background-color: #c1c1c1;
}
 
label.bui-radios-label.bui-radios-anim .bui-radios {
  -webkit-transition: background-color ease-out .3s;
  transition: background-color ease-out .3s;
}

完整的单选框 radio ,多选框 checkbox 和 switch 开关 demo示例:www.css88.com/demo/beauti…

这里有几点需要说明的是:
1. checkbox 中的 勾勾使用了iconfont,当然你可以改下图片,或用伪类(:before:after)模拟。
2. 添加了一些简单的过渡效果 或 背景动画。
3. 特别重要的一点是:利用 label 标签的特性,对于HTML基础不好同学来说,请先了解一下 label 标签的特性。

关注WEB前端开发官方公众号

关注国内外最新最好的前端开发技术干货,获取最新前端开发资讯,致力于打造高质量的前端技术分享公众号