• 主页
  • 个人简介
    • 圣墨 photo

      圣墨

      一个爱折腾,有诗有远方的人

    • Learn More
    • Github
    • Cnblogs
    • Weibo
  • 文章
    • 所有文章
    • 所有标签
  • Html&Css
  • Javascript
  • 设计模式
  • 前端性能优化
  • 原生实现专题
  • 数据结构与算法
  • Book
  • 面试题
  • 前端工具
  • 随记

自定义checkbox样式

12 Dec 2017

Reading time ~1 minute

自定义checkbox样式

关键点

  • label的for属性可以关联一个具体的input元素
  • 隐藏input元素,然后修改label样式

1、复选框样式

html

    <input type="checkbox" id="inputId">
    <label for="inputId"></label>

css

  input {
      display: none;
    }
  label {
      display: inline-block;
      width: 20px;
      height: 20px;
      border-radius: 5px;
      border: 1px solid #2eb5f0;
      position: relative;
      cursor: pointer;
  }
  label::before {
      display: inline-block;
      content: " ";
      width: 12px;
      border: 2px solid #fff;
      height: 4px;
      border-top: none;
      border-right: none;
      transform: rotate(-45deg);
      top: 5px;
      left: 3px;
      position: absolute;
      opacity: 0;
  }
  input:checked+label {
      background: #2eb5f0;
  }
  input:checked+label::before{
      opacity: 1;
      transform: all 0.5s;
  }

2、单选框

html

  <input type="radio" id="radioId">
  <label for="radioId"></label>

css

  label {
      display: inline-block;
      width: 20px;
      height: 20px;
      border-radius: 50%;
      border: 1px solid #2eb5f0;
      position: relative;
      cursor: pointer;
  }
  label::before {
      content: " ";
      display: inline-block;
      width: 7px;
      height: 7px;
      background-color: #fff;
      border-radius: 50%;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
  }
  input[type=radio] {
      display: none;
  }
  input[type=radio]:checked+label {
      background-color: #2eb5f0;
  }

3、switch开关

html

  <input type="checkbox" id="checkId" checked>
  <label for="checkId"></label>

css

  label {
      position: relative;
      display: inline-block;
      width: 40px;
      height: 20px;
      background-color: red;
      border-color: red;
      border-radius: 10px;
  }
  label::before {
      content: " ";
      display: inline-block;
      width: 16px;
      height: 16px;
      border-radius: 50%;
      position: absolute;
      right: 22px;
      top: 2px;
      background-color: #fff;
      transition: all 0.4s ease;
      cursor: pointer;
  }
  input {
      display: none;
  }
  input:checked+label {
      background-color: rgb(19, 206, 102);
      border-color: rgb(19, 206, 102);
  }
  input:checked+label::before {
      right: 2px;
  }


markdown Html css  微博  QQ  朋友圈