Radio buttons simulated using CSS

Summary

Principle

Radio buttons are form elements that allow the user to select one unique option among a group of possible options.

Radio buttons are “simulated using CSS” when they are not built using the standard HTML code for radio buttons as found in the specification <input type="radio" /> but the standard radio buttons are visually hidden and replaced with CSS images, icon fonts, or specific styles.

There are several ways of achieving this. The example below shows how to simulate radio buttons using CSS pseudo-elements and background images, while retaining their accessibility.

Core HTML base

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

CSS base

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

In the CSS, background images are then placed correctly over the radio buttons. For example:

input[type="radio"] + 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