Toggle Switch Template
A stylish and accessible toggle switch for enabling or disabling options with a single click.
This component provides a more intuitive and visually appealing alternative to a traditional checkbox for binary choices, such as toggling dark mode or notifications.
About the Toggle Switch
Toggle switches offer a clean and modern way to present a simple on/off choice. This template uses a clever CSS technique to style a semantic HTML checkbox, resulting in a beautiful switch that is fully accessible and requires no JavaScript for its basic functionality.
Features
- Pure CSS Functionality: The sliding animation and state change are handled entirely by CSS, making the component lightweight and fast.
- Accessible Foundation: Built using a
labeland a standardinputwithtype="checkbox". This ensures it's keyboard-navigable and correctly interpreted by screen readers. The addedrole="switch"makes its purpose even more explicit. - Smooth Animation: A gentle
transitioncreates a smooth sliding effect for the switch's handle. - Easy to Customize: All colors and sizes can be quickly adjusted using the CSS variables at the top of the style block.
Code Breakdown
The structure consists of a checkbox input and an associated label. The checkbox itself is visually hidden, but remains functional in the background. The label is styled to look like the track of the switch.
The "toggle" part happens with the :checked pseudo-class and the adjacent sibling selector (+). When the checkbox is checked, the rule .toggle-checkbox-1:checked + .toggle-label-1 triggers, changing the background color of the label. Similarly, a rule targeting the label's ::after pseudo-element, which serves as the handle, uses a transform to slide the handle to the "on" position.
Code
Here is the complete HTML and CSS for the accessible toggle switch.