Introducing the Web Design Pattern with a Twist!
The concept of a “switch” is a familiar design pattern on the web. It’s essentially a checkbox. In reality, it should be an <input type="checkbox">
or even a <select>
with a couple of <option>
tags (or a third for an indeterminate state) under the HTML hood.
However, the web doesn’t offer a primitive element that visually resembles a switch-like toggle. This is where CSS comes to the rescue. By using CSS, we style elements that appear to be switch-like, giving the illusion of flipping a knob on and off.
Are you intrigued? Check out this classic example.
Picture using this switch-like concept for toggling email notification settings or switching a site between dark and light modes. We implement them frequently at CodePen for various features like privacy settings for Pens.
Have you explored the challenges of implementing a dark mode toggle? Read about it in Aleksandr Hovhannisyan’s article. It’s not as straightforward as you might think. Consider system-level preferences, site-level preferences, and ensuring smooth transitions without flashing incorrect colors. Aleksandr dives into the nitty-gritty details and shares helpful resources.
Let’s shift the focus back to switches!
Recently, Jen Simmons mentioned that Safari is experimenting with a native switch. Here’s the HTML:
<input type="checkbox" switch>
Here’s how it looks by default:
Exciting, right? The native iOS toggle is brought to life, customizable with CSS’s accent-color
. It offers clear pseudo elements like ::thumb
and ::track
, opening up new styling possibilities.
.custom-switch { }
.custom-switch::thumb { }
.custom-switch::track { }
.custom-switch:checked::thumb { }
.custom-switch:checked::track { }
.custom-switch::checked::after { }
.custom-switch::checked::before { }
For impressive demos, check out Tim Nguyen’s creations here.
By leveraging these browser-provided elements, we eliminate accessibility concerns while gaining design flexibility. As long as the checkbox follows standard form structure, you’re good to go. Embrace the visual control but ensure clarity in checked and unchecked states for user understanding.