How to style a checkbox using CSS

前端 未结 30 3429
日久生厌
日久生厌 2020-11-21 04:26

I am trying to style a checkbox using the following:

30条回答
  •  无人共我
    2020-11-21 05:03

    You can style checkboxes with a little trickery using the label element an example is below:

    .checkbox > input[type=checkbox] {
      visibility: hidden;
    }
    
    .checkbox {
      position: relative;
      display: block;
      width: 80px;
      height: 26px;
      margin: 0 auto;
      background: #FFF;
      border: 1px solid #2E2E2E;
      border-radius: 2px;
      -webkit-border-radius: 2px;
      -moz-border-radius: 2px;
    }
    
    .checkbox:after {
      position: absolute;
      display: inline;
      right: 10px;
      content: 'no';
      color: #E53935;
      font: 12px/26px Arial, sans-serif;
      font-weight: bold;
      text-transform: capitalize;
      z-index: 0;
    }
    
    .checkbox:before {
      position: absolute;
      display: inline;
      left: 10px;
      content: 'yes';
      color: #43A047;
      font: 12px/26px Arial, sans-serif;
      font-weight: bold;
      text-transform: capitalize;
      z-index: 0;
    }
    
    .checkbox label {
      position: absolute;
      display: block;
      top: 3px;
      left: 3px;
      width: 34px;
      height: 20px;
      background: #2E2E2E;
      cursor: pointer;
      transition: all 0.5s linear;
      -webkit-transition: all 0.5s linear;
      -moz-transition: all 0.5s linear;
      border-radius: 2px;
      -webkit-border-radius: 2px;
      -moz-border-radius: 2px;
      z-index: 1;
    }
    
    .checkbox input[type=checkbox]:checked + label {
      left: 43px;
    }

    And a FIDDLE for the above code. Note that some CSS doesn't work in older versions of browsers, but I'm sure there are some fancy JavaScript examples out there!

提交回复
热议问题