复选框, 单选框都不好直接用 CSS 样式美化, 总得用点奇思妙想才行. 如果只考虑谷歌内核的浏览器的话, 那么用 appearance 属性可以搞定大部分表单控件的样式. 关键是这个 appearance 属性 IE 不支持, 这就逼得大家另想办法了.
利用 label 挂钩 checkbox 的特点来实现.
当 html 代码中, label 的 for 属性值和 checkbox 的 id 值一样的时候, label 就可以控制 checkbox 的选择了.
HTML 代码如下:
- <div id="check">
- <input type="checkbox" id="btn-check">
- <label for="btn-check"><span > 全天 </span></label>
- </div>
为 label 的伪元素添加背景图片, 覆盖真正的 checkbox 对象, 这样, 既有图片的美观效果, 又有 checkbox 一切的交互行为.
设计一个图片如下, 默认状态, 点击状态, 不可用状态.(相关课程推荐: CSS 视频教程 https://www.html.cn/css/ )
这里使用了定位, 不然不能覆盖原始的复选框. 而且文字和图片之间要间隔, 文字也需要设置为定位对象. 总之, 这里都是定位关系.
这个效果只兼容 IE9 以上.
- CSS
- #check {
- position: relative;
- }
- input[type=checkbox]+label {
- position: absolute;
- width: 60px;
- height: 20px;
- }
- input[type=checkbox]+label:before {
- content: "";
- position: absolute;
- width: 20px;
- height: 20px;
- background: url(images/btn1.PNG) no-repeat;
- }
- input[type=checkbox]+label span {
- font-size: 14px;
- position: absolute;
- left: 30px;
- }
- input[type=checkbox]:checked+label:before {
- background-position: -28px 0;
- }
- input[type=checkbox] {
- position: absolute;
- left: 0;
- top: 0;
- }
本文来自 CSS 答疑 https://www.html.cn/qa/css3/ 栏目, 欢迎学习!
来源: http://www.css88.com/qa/css3/14809.html