Last Updated: February 25, 2016
·
2.27K
· robsn

Custom checkbox & radio input with pure css and fallback


INTRO: I am currently working on a new styleguideline and here is my pro tip for customizing checkboxes and radio buttons with pure CSS3 and a implicit fallback to native.

+ First we create to divs with classes 'checkbox' and 'radio' like so:

div.checkbox
div.radio

+ Then insert the input fields for type radio and type checkbox like so:

div.checkbox>input#chkbx[type=checkbox]+label[for=chkbx]
div.radio>input#rdo[type=radio]+label[for=rdo]

INFO: So yes, I am using Emmet, if you don't know it, you should really check it out ;-)

+ CSS Part ist next: Let's hide the native inputs:

.checkbox input:checked, 
.checkbox input:not(checked),
.radio input:checked, 
.radio input:not(checked) {
    display: none !important;
}

+ And add some base styles wich we rely on:

.checkbox label, .radio label{
  display: inline-block;
  position: relative;
}
.checkbox input:checked + label, 
.checkbox input:not(checked) + label,
.radio input:checked + label, 
.radio input:not(checked) + label {

  padding-left: 25px;
  padding-bottom: 1px;
  font-size: 13px;
  cursor: pointer;
}

INFO: I am explicit selecting :checked and :not(checked) for this reason:
For Browser not supporting :checked my ruleset won't apply so the native input will be displayed.

+ Now we add Pseudo Elements to our labels for checked and unchecked states:

.checkbox input:not(checked) + label:before {
  border: 1px solid #CFCFCF;
  content: "";
  display: inline-block;

  width: 14px;
  height: 14px;

  margin-right: 10px;
  position: absolute;
  left: 0;
  bottom: 1px;

}
.checkbox input:checked + label:before{
  border: 1px solid #3E3E3E;
  color: #3E3E3E;
  content: "\2713";
  font-size: 17px;
  text-align: center;
  line-height: 13px;
  font-weight: bold;
}

+ Same for radio styling:

.radio input:not(checked) +label:after,{
  border: 1px solid #CFCFCF;
  content: "";
  display: inline-block;
  height: 14px;
  width: 14px;
  left: 0;
  bottom: 1px;
  position: absolute;
  text-align: center;
  font-size: 13px;
  line-height: 15px;
  font-weight: bold;
}
.radio label:after {
  border-radius: 8px;
}
.radio input:checked + label:after{
  border-color: #3E3E3E;
  background-color: #3E3E3E;
  box-shadow: 0 0 0 2px #FFFFFF inset;

}

INFO: Check out a working example at Codepen: http://codepen.io/Robsn/full/Ihgiy

Have fun customizing !