Checkboxes customized using CSS

Summary

Principle

Checkboxes are form elements that are used to select one or more options out of a group of options.

Checkboxes are “customized using CSS” when they are built using the standard HTML code as found in the specification <input type="checkbox" /> but the standard visual checkboxes are hidden off screen and simulated with CSS images, icon fonts or specific styles.

There are several ways of achieving this. The example below shows how to simulate the behavior of a standard default HTML checkbox using CSS pseudo elements and background images, while ensuring that they remain accessible.

Core HTML base

<fieldset>
  <legend>Question</legend>
    <ul>
      <li>
        <input type="checkbox" id="answer-1" name="answer-1" />
        <label for="answer-1">Answer 1</label>
      </li>
      <li>
        <input type="checkbox" id="answer-2" name="answer-2" />
        <label for="answer-2">Answer 2</label>
      </li>
      […]
    </ul>
</fieldset>

CSS base

label {
  position: relative;
  padding: 0 0 0 2rem;
}

input[type=checkbox] {
  position: absolute;
  opacity: 0;
}

input[type=checkbox] + label::before,
input[type=checkbox] + label::after {
  content: '';
  position: absolute;
  display: inline-block;
}

input[type=checkbox] + label::before {
  left: 0.5rem;
  top: 0.15rem;
  width: 0.9rem;
  height: 0.9rem;
  border: 0.05rem solid black;
  background: white;
}

input[type=checkbox]:checked + label::after {
  left: 0.6rem;
  top: 0.28rem;
  height: 0.8rem;
  border-left: 0.8rem solid black;
}

input[type=checkbox]:focus + label::before {
  outline: 0.05rem dotted;
}

Demo

Question?

Comments

Add a comment

Required fields are marked *.

Back to top