原码笔记

原码笔记

使用纯CSS的复选框和单选按钮的自定义样式示例代码

小诸哥 0

首先看看不同平台的checkbox & radio


我们可以利用css3的一些属性来实现自定义checkbox & radio样式。

HTML 代码

  1. // radio input
  2. <div class="radio">
  3.      <input id="male" type="radio" name="gender" value="male">
  4.      <label for="male">Male</label>
  5.      <input id="female" type="radio" name="gender"; value="female">
  6.      <label for="female">Female</label>
  7. </div>
  8.  
  9.  
  10. // checkbox input
  11. <div class="checkbox">
  12.      <input id="check1" type="checkbox" name="check" value="check1">
  13.      <label for="check1">Checkbox No. 1</label>
  14.  
  15.      <input id="check2" type=&quot;checkbox" name="check" value="check2">
  16.      <label for="check2">Checkbox No. 2</label>
  17. </div>

CSS 代码

  1. label {
  2.      display: inline-block;
  3.      cursor: pointer;
  4.      position: relative;
  5.      padding-left: 25px;
  6.      margin-right: 15px;
  7.      font-size: 13px;
  8. }
  9.  
  10. label:before {
  11.      content: "";
  12.      display: inline-block;
  13.  
  14.      width: 16px;
  15.      height: 16px;
  16.  
  17.      margin-right: 10px;
  18.      position: absolute;
  19.      left: 0;
  20.      bottom: 1px;
  21.      background-color: #aaa;
  22.      box-shadow: inset 0px 2px 3px 0px rgba(0, 0, 0, .3), 0px 1px 0px 0px rgba(255, 255, 255, .8);
  23. }
  24.  
  25. .radio label:before {
  26.      border-radius: 8px;
  27. }
  28. .checkbox label:before {
  29.      border-radius: 3px;
  30. }
  31.  
  32.  
  33. input[type=radio],
  34. input[type=checkbox] {
  35.      display: none;
  36. }
  37.  
  38. input[type=radio]:checked + label:before {
  39.      content: "\2022";
  40.      color: #f3f3f3;
  41.      font-size: 30px;
  42.      text-align: center;
  43.      line-height: 18px;
  44. }
  45. input[type=checkbox]:checked + label:before {
  46.      content: "\2713";
  47.      text-shadow: 1px 1px 1px rgba(0, 0, 0, .2);
  48.      font-size: 15px;
  49.      color: #f3f3f3;
  50.      text-align: center;
  51.      line-height: 15px;
  52. }


兼容性

:checked在IE8兼容性不理想

box-shadow在IE8不兼容,不过box-shadow对于自定义样式可有可无

:after :before在IE8不兼容双冒号写法

:checked属性兼容性

box-shadow属性兼容性

:before :after属性兼容性

总结

以上就是这篇文章的全部内容,希望本文的内容对大家的学习或者工作能有所帮助,如果有疑问大家可以留言交流。

标签: 复选框 单选按钮