Checkboxes simulated using CSS

Sommaire

Principle

Checkboxes are form elements that allow the user to select one or more options among a group of options.

Checkboxes are “simulated 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 af 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

input[type="checkbox"] {
  position: absolute;
  z-index: 100;
}
input[type="checkbox"]:focus + label {
  outline: 1px dotted;
}
input[type="checkbox"] + label::before {
  position: relative;
  z-index: 200;
  content: url('checkbox.png');
}
input[type="checkbox"]:checked + label::before {
 content: url('checkbox-checked.png');
} 

In the CSS, background images are placed accurately over the checkboxes which have been hidden using the code below, for example:

input[type="checkbox"] + label::before {
  width: 1.5em;
  height: 1.5em;
  display: inline-block;
}

Demo

Question?

Examples of components

The following components are proposed here because their level of accessibility is considered good or very good.

However, before using them in your project, it is important to check that the specifications presented above have been respected. Depending on the version used, the components may need some adjustments before they can be used in your project.

Comments

Add a comment

Required fields are marked *.

Back to top