css写复选框

前面讲过《完全使用css编写复选框》,后来在深入学习sass过程中,发现:这种写法虽然也能达到目的,但是稍嫌复杂了一点。这里介绍一种可以说更简单一点的方法,其实也就是html结构更简单一点,就css而言,也差不多吧。

还是以复选框为例吧。

<label><input type="checkbox" name="name" checked />选项一</label>

  其实核心的html结构也就是我们正常使用的input[type=checkbox]的写法,关键在于可以用css清除其默认样式,这是我之前一直忽略或者说完全不知情的一条css语句。

input[type=checkbox]{
   -webkit-appearance: none;
           appearance: none;   
}

  appearance: none;   清除了整个[type=checkbox]的默认样式,由于涉及到兼容性的问题,一般主要用于移动端的清除复选框和单选框的默认样式。

input[type=checkbox]{
  -webkit-appearance: none;
          appearance: none; 
  display: inline-block;
  cursor: pointer;
  vertical-align: middle;
  background-repeat: no-repeat;
  -webkit-transition: background-position .15s cubic-bezier(.8, 0, 1, 1),
                      -webkit-transform .25s cubic-bezier(.8, 0, 1, 1);
          transition: background-position .15s cubic-bezier(.8, 0, 1, 1),
                      -webkit-transform .25s cubic-bezier(.8, 0, 1, 1);
  outline: none;   
   24px;
  height: 24px;
  margin: 0 6px;
  background-image: url(default.png);
  background-size: 75% 75%;
  -webkit-box-shadow: hsla(0,0%,100%, .15) 0 1px 1px, inset hsla(0,0%,0%,.5) 0 0 0 1px;
              box-shadow: hsla(0,0%,100%, .15) 0 1px 1px, inset hsla(0,0%,0%,.5) 0 0 0 1px;       
  border-color: #ff7b11;  
}
input[type=checkbox]:checked{
  -webkit-transition: background-position .2s .15s cubic-bezier(0, 0, .2, 1),
                          -webkit-transform .25s cubic-bezier(0, 0, .2, 1);
              transition: background-position .2s .15s cubic-bezier(0, 0, .2, 1),
                          -webkit-transform .25s cubic-bezier(0, 0, .2, 1);
}

input[type=checkbox]:active{
    -webkit-transform: rotate(45deg);
                transform: rotate(45deg);
    -webkit-transition: -webkit-transform .1s cubic-bezier(0, 0, .2, 1);
              transition: -webkit-transform .1s cubic-bezier(0, 0, .2, 1);
}
input[type=checkbox],
input[type=checkbox]:active,
input[type=checkbox]:checked ~ input[type=checkbox],
input[type=checkbox]:checked ~ input[type=checkbox]:active {
      background-position: center  -24px;
}
input[type=checkbox]:checked {
      background-position: center center;
}

  这就实现自定义的checkbox样式了,再也不用使用各种标签,并通过js模拟来实现简单的单选和复选框的问题了。  

原文地址:https://www.cnblogs.com/zhuhuoxingguang/p/7654676.html