Switch Component

A switch requires the switch role and aria-checked attribute for assistive technology.

REMEMBER: every switch requires a visible, programmatic label to indicate its purpose.

Default Switch

The default version of the switch requires JavaScript to maintain the aria-checked state when clicked.

The switch__control child element requires a tabindex value of 0 (zero) to be keyboard focusable.

<span class="switch">
  <span
    class="switch__control"
    role="switch"
    tabindex="0"
    aria-checked="false"
  />
  <span class="switch__button" />
</span>

Disabled Switch

To disable a switch, apply the aria-disabled attribute.

The tabindex property must be set to -1 (negative one) to prevent keyboard focus.

<span class="switch">
  <span
    class="switch__control"
    role="switch"
    tabindex="-1"
    aria-checked="false"
    aria-disabled="true"
  />
  <span class="switch__button" />
</span>

Checkbox Switch

This version of the switch uses a checkbox under the hood. It should be used if you require the switch to store data inside of a form. As mentioned above however, this is not the intended purpose of a switch. You may wish to consider using an actual checkbox instead.

<span class="switch">
  <input
    class="switch__control"
    role="switch"
    type="checkbox"
    aria-checked="false"
  />
  <span class="switch__button" />
</span>

Disabled Checkbox Switch

To disable a checkbox switch, apply the disabled attribute.

<span class="switch">
  <input
    class="switch__control"
    role="switch"
    type="checkbox"
    aria-checked="false"
    disabled
  />
  <span class="switch__button" />
</span>

Custom Properties of Switch EXPERIMENTAL

The following custom properties (aka CSS Variables) are available for system color-scheme appearance (i.e. light-mode & dark-mode) and other general theming purposes:

  • --switch-unchecked-background-color
  • --switch-checked-background-color
  • --switch-disabled-background-color
  • --switch-foreground-color
  • --switch-unchecked-hover-background-color
  • --switch-checked-hover-background-color
<style>
  .switch--theme-1 {
    --switch-unchecked-background-color: orange;
    --switch-checked-background-color: green;
    --switch-unchecked-hover-background-color: coral;
    --switch-checked-hover-background-color: limegreen;
  }

  @media (prefers-color-scheme: dark) {
    .switch--theme-1 {
      --switch-unchecked-background-color: blue;
      --switch-checked-background-color: red;
      --switch-unchecked-hover-background-color: purple;
      --switch-checked-hover-background-color: indianred;
    }
  }
</style>
<span class="switch switch--theme-1">
  <span
    class="switch__control"
    role="switch"
    tabindex="0"
    aria-checked="false"
  />
  <span class="switch__button" />
</span>