Tuesday 2 May 2017

Custom Check/Radio boxes

Vanilla check and radio boxes in your web browser look plane and ugly, everyone wants nicely styled and modern looking controls; there's many jquery widgets, that do this for you but what if i told you there was a simple solution using only css and no javascript.

the idea is to leverage the pseudo selector :checked,

here's our html, pretty simple just a label wrapping two spans letting us toggle the checkbox by clicking the content of the label.

<label>
    <input type="checkbox" />
    <span></span>
    <span>my checkbox</span>

</label>

and now the magic our css

label > input[type=checkbox] {
  display: none;
}

label > input[type=checkbox] + span {
  width: 20px;
  height: 20px;
  border: solid 1px #ccc;
  display: inline-block;
}

label > input[type=checkbox] + span:before {
  content: '\2713';
  color: transparent;
  display: block;
}

label > input[type=checkbox]:checked + span:before {
  content: '\2713';
  color: black;
  display: block;
  text-align: center;
}

label > input[type=checkbox] + span + span {
  user-select: none;

}

normally i'd use SCSS but figure why not make it vanilla