lulujianglab / blog

:bento:lulujiang blog
https://lulujianglab.com/
83 stars 4 forks source link

css实现自定义复选框样式 #10

Open lulujianglab opened 6 years ago

lulujianglab commented 6 years ago

前言

浏览器自带的checkbox复选框不怎么美观,而且复选框在不同的浏览器上显示的样式又有很大的差异

目的

用一些css代码来自定义checkbox的显示方式,比如框中的√颜色变为绿色

方法

通过appearance去修改css默认样式

html:
<input type="checkbox" id="awesome" />
<label for="awesome"></label>

css:
input[type="checkbox"]{
  -webkit-appearance: none;
  top: 5px;
  float: left;
  position: relative;
  vertical-align:middle;
  margin-top:0;
  background:#fff;
  border:#dedede solid 1px;
  border-radius: 3px;
  min-height: 14px;
  min-width: 14px;
}
input[type="checkbox"]:focus {
  outline: none;
}
input[type=checkbox]:checked::after{
  content: '';
  top: 1px;
  left: 1px;
  position: absolute;
  vertical-align: middle;
  margin-top: 0;
  background: transparent;
  border: #85de82 solid 2px;
  border-top: none;
  border-right: none;
  height: 4px;
  width: 8px;
  -moz-transform: rotate(-45deg);
  -ms-transform: rotate(-45deg);
  -webkit-transform: rotate(-45deg);
  transform: rotate(-45deg);
}

原理比较简单,通过css的appearance属性去修改css默认样式

appearance是css3的新属性,所有主流浏览器都不支持appearance,所以让chrome支持用-webkit-appearance

利用label标签的模拟功能

html:
<input type="checkbox" id="awesome" />
<label for="awesome"></label>

css:
input[type="checkbox"] + label::before {
  content: ' ';
  display: inline-block;
  vertical-align: .2em;
  width: .8em;
  height: .8em;
  margin-right: .2em;
  border-radius: .2em;
  background: silver;
  text-indent: .15em;
  line-height: .65;
}
input[type="checkbox"]:checked + label::before {
  content: '\2713';
  color: #85df82;
}
input[type="checkbox"] {
  position: absolute;
  clip: rect(0,0,0,0);
}

主要思路:

label的for属性可以关联一个具体的input元素,即使这个input本身不可被用户可见,有个与它对应的label后,我们就可以直接通过和label标签交互来替代原生的input(比如相邻选择符(E+F),伪元素after,before,可以直接利用html的默认checkbox)

一句话概括就是隐藏原生input,样式定义的过程留给label

使用自定义图片来实现checkbox的显示

html:
        <input  type="checkbox"  id="checkbox01" />
       <label  for="checkbox01"></label>

css:
/* 隐藏checkbox */
input[type='checkbox'] {
display: none;
}
/* 对label进添加背景图片*/
label {
  display: inline-block;
  width: 60px;
  height: 60px;
  position: relative;
  background: url(unchecked.png);
  background-repeat: no-repeat;
}
 input[type='checkbox']:checked + label {
  width: 60px;
  height: 60px;
  position: relative;
  background: url(checked.png);
  background-repeat: no-repeat;
   }