Back to DocsUX Pattern
Recipe: Toggle Switch
A native-feeling toggle switch built with pure Tailwind. No libraries, no JavaScript — just CSS peer selectors and a hidden checkbox.
Live Preview
Enable notifications
How It Works
- Hidden
sr-onlycheckbox drives state via Tailwind'speermodifier. - The track is a
divwith rounded-full; the thumb is theafter:pseudo-element. peer-checked:bg-[#8B5CF6]colors the track violet when on.- Thumb slides 20px right via
peer-checked:after:translate-x-[20px].
Copy-Paste Code
<label class="relative inline-flex cursor-pointer items-center">
<input type="checkbox" class="peer sr-only" />
<div class="h-7 w-12 rounded-full bg-gray-700
transition-colors peer-checked:bg-[#8B5CF6]
after:absolute after:left-[3px] after:top-[3px]
after:h-[22px] after:w-[22px] after:rounded-full
after:bg-white after:transition-transform
peer-checked:after:translate-x-[20px]" />
</label>Accessibility note: The hidden checkbox preserves keyboard focus and screen-reader state. Always pair with a visible label so users know what the toggle controls.