CSS only checkbox

a11y compatible CSS only checkboxes

by Andrew Bone

HTML

<fieldset>
  <legend>Accessible Checkboxes</legend>

  <label class="md_checkbox">
    <input type="checkbox" />
    <span class="md_checkbox__tick"></span>
    Checkbox
  </label>

  <label class="md_checkbox">
    <input checked type="checkbox" />
    <span class="md_checkbox__tick"></span>
    Pre-checked
  </label>

  <label class="md_checkbox">
    <input disabled type="checkbox" />
    <span class="md_checkbox__tick"></span>
    Disabled
  </label>

  <label class="md_checkbox">
    <input checked disabled type="checkbox" />
    <span class="md_checkbox__tick"></span>
    Checked and disabled
  </label>

  <label class="md_checkbox">
    <input type="checkbox" />
    <span class="md_checkbox__tick"></span>
    Really really really long label content to hopefully span several lines to show that the checkbox will stay central.
  </label>
</fieldset>

CSS

@import url(http://fonts.googleapis.com/css?family=Open+Sans);
.md_checkbox {
  display: flex;
  font-family: "Open Sans";
  align-items: center;
  margin: 2px 0;
}

.md_checkbox [type=checkbox] {
  position: absolute;
  opacity: 0;
  pointer-events: none;
}

.md_checkbox .md_checkbox__tick {
  position: relative;
  cursor: pointer;
}

.md_checkbox .md_checkbox__tick::before {
  content: '';
  display: block;
  margin: 0 3px;
  height: 18px;
  width: 18px;
  border: 2px #CFD8DC solid;
  border-radius: 3px;
}

.md_checkbox [type=checkbox]:focus+.md_checkbox__tick::before {
  outline: #5d9dd5 solid 1px;
  box-shadow: 0 0px 8px #5e9ed6;
}

.md_checkbox [type=checkbox]:checked+.md_checkbox__tick::before {
  background: #3700B3;
  border-color: #3700B3;
}

.md_checkbox [type=checkbox]:disabled+.md_checkbox__tick::before {
  background: #CFD8DC;
  border-color: #CFD8DC;
}

.md_checkbox [type=checkbox]+.md_checkbox__tick::after {
  content: 'âś“';
  position: absolute;
  line-height: 18px;
  text-align: center;
  color: white;
  top: 0px;
  left: 0px;
  margin: 0 3px;
  height: 18px;
  width: 18px;
  border: 2px rgba(0, 0, 0, 0) solid;
  opacity: 0;
}

.md_checkbox [type=checkbox]:checked+.md_checkbox__tick::after {
  opacity: 1;
}