On this page
The switch button

Native toggle switch button with fallback using HTML and CSS only

Learn to create a native toggle switch button, including fallback options for better compatibility.

You can create a native toggle switch button using only HTML and CSS by using a checkbox input and styling it accordingly.

However, there is also a way to use the switch attribute that turns the native checkbox into the switch button.

Understanding the switch attribute in Safari

Safari 17.4 introduces a native UI toggle switch control, a feature not yet included in the HTML specification. However, you can still leverage this new control as a progressive enhancement on top of the standard <input type="checkbox"> element, making it accessible to users with Safari 17.4 or later.

Example of input type checkbox with the switch attribute
<input type="checkbox" switch>
<input type="checkbox" checked switch>
macOS, Safari and rendered input type checkbox with the switch attribute
macOS, Safari and rendered input type checkbox with the switch attribute
macOS VoiceOver screenshot that shows switch and on state
macOS VoiceOver screenshot that shows switch and "on" status

Creating a robust solution for switch attribute support

To create a solution that works with checkboxes and handles the switch attribute, you can use a combination of HTML, CSS, and JavaScript.

There could be used the CSS rule @supports selector(::thumb) {} to determine if switch is supported, but it will only work in the Safari browser.

In our scenario, we need to use JavaScript if ("switch" in document.createElement("input")) to determine if the attribute switch is supported, and implement a fallback solution if it is not.

Below is an example of how to create a toggle switch button that works as a checkbox, with a fallback for browsers that do not support the switch attribute. We’ll also ensure that is accessible.

An important case to note is that input[type="checkbox"] can have an indeterminate state, whereas input[switch] cannot.

Interactive demos: exploring the switch functionality

Native switch button with fallback using HTML, CSS, and JavaScript. Try to run the following examples in different browsers, including Safari, to see the differences.

  • Toggle switch with HTML and CSS only.
  • Toggle switch with HTML and CSS only, but with text label.
  • Toggle switch using input type checkbox and switch attribute with fallback.
  • Toggle switch using input type checkbox and switch attribute only.

Related posts

Comments

Leave a Reply

Search in sitelint.com

Struggling with writing tests for accessibility?

You can cut 80% of the time you spend writing tests using SiteLint.

Real-user monitoring for Accessibility, Performance, Security, SEO & Errors (SiteLint)