Toggle Switch Generator
Build a toggle switch with size, knob inset, colours and animation speed. Clickable preview, copy the CSS and HTML.
Click the switch to toggle its state.
.switch { position: relative; display: inline-block; width: 56px; height: 30px; }
.switch input { opacity: 0; width: 0; height: 0; }
.slider {
position: absolute; inset: 0; cursor: pointer;
background: #2a2f3d; border-radius: 30px;
transition: background 0.25s ease;
}
.slider::before {
content: ""; position: absolute; height: 24px; width: 24px;
left: 3px; bottom: 3px; background: #ffffff;
border-radius: 50%; transition: transform 0.25s ease;
}
input:checked + .slider { background: #6d5efc; }
input:checked + .slider::before { transform: translateX(26px); }
<!-- HTML:
<label class="switch"><input type="checkbox" checked><span class="slider"></span></label> -->About the toggle switch generator
A toggle switch is a checkbox in disguise. The real input is hidden but still present, so keyboard focus and form submission keep working, while a styled span provides the track and the knob.
Building it this way rather than with a div and a click handler is what keeps it accessible for free.
How to use it
- 1Set the width and height. Roughly a 2:1 ratio reads as a switch.
- 2Adjust the knob inset, which is the gap between knob and track.
- 3Pick on, off and knob colours.
- 4Set the animation speed. Around 0.25 seconds feels responsive.
- 5Copy the CSS and HTML.
Worth knowing
- The hidden input keeps keyboard and screen reader support intact. Do not replace it with a div.
Questions
Why hide a real checkbox instead of using a div?
Because the checkbox gives you keyboard focus, space-bar toggling, form submission and screen reader semantics with no extra work. A div gives you none of that.
When should I use a switch instead of a checkbox?
A switch is for a setting that applies immediately. A checkbox is for a choice that takes effect when a form is submitted.
How do I add a focus ring?
Style .switch input:focus-visible + .slider. Never remove the focus indicator without replacing it.