The “switch” is a commonly used design pattern on the web. It functions similarly to a checkbox, and can be implemented using the HTML tags or
However, there is no built-in switch-like primitive in HTML, so CSS is used to style it. The checkbox is hidden in some way to maintain a clickable area, and the :checked selector is used to style the switch-like appearance.
Here is a classic example:
This switch can be used for various purposes, such as toggling email notification settings or switching between dark mode and light mode on a website.
Speaking of dark mode toggles, Aleksandr Hovhannisyan has written an article about the challenges of implementing a dark mode toggle. It involves considering system-level and site-level preferences, setting controls correctly, and styling the site without displaying incorrect colors. Aleksandr provides a thorough explanation and links to other helpful resources. It’s a complex task that could benefit from browser and standards involvement, although a perfect solution is not yet clear.
Now, let’s get back to switches!
Jen Simmons mentioned that Safari is experimenting with a native switch. Here is the HTML:
Isn’t it nice?
By default, it looks like this:
Not surprisingly, it resembles the native iOS toggle. It follows the accent-color in CSS like other form controls, which is great. Moreover, it provides sensible pseudo elements that can be styled. There are ::thumb and ::track elements, as well as ::before and ::after elements for further customization.
To style the native switch, you can use the following CSS:
.custom-switch { }
.custom-switch::thumb { }
.custom-switch::track { }
.custom-switch:checked::thumb { }
.custom-switch:checked::track { }
.custom-switch::checked::after { }
.custom-switch::checked::before { }
Tim Nguyen has created demos that demonstrate the possibilities using clean and readable CSS.
The best part of browsers providing native switches is that accessibility is taken care of. As long as you follow the standard HTML structure of a labeled checkbox in a form, accessibility is ensured. You have control over the visual appearance, but make sure the checked and unchecked values are clearly distinguishable.