CSS Toggle Switch: Build One Without JavaScript (Step-by-Step)
Learn how to build a pure CSS toggle switch with no JavaScript. Step-by-step tutorial with accessible HTML, smooth animations, and dark mode integration.
Lead Developer, UIsen
Why Pure CSS Toggle Switches?
A pure CSS toggle switch requires zero JavaScript, making it lightweight, fast, and accessible by default. It uses a standard HTML under the hood, so form libraries and screen readers understand it natively.
In this tutorial, you'll build a smooth iOS-style toggle switch with animation — entirely in CSS.
Step 1: HTML Structure
The toggle needs only two elements — a hidden checkbox and a styled label:
``html
``
The checkbox is the actual form control. The span becomes the visual toggle track and knob (via pseudo-elements).
Step 2: CSS Styling
``css
.toggle__input {
position: absolute;
opacity: 0;
width: 0; height: 0;
}
.toggle__track {
display: block;
width: 52px; height: 28px;
background: #3f3f46;
border-radius: 14px;
position: relative;
cursor: pointer;
transition: background 0.3s ease;
}
.toggle__track::after {
content: '';
position: absolute;
top: 3px; left: 3px;
width: 22px; height: 22px;
background: white;
border-radius: 50%;
transition: transform 0.3s ease;
}
.toggle__input:checked + .toggle__track {
background: #6366f1;
}
.toggle__input:checked + .toggle__track::after {
transform: translateX(24px);
}
``
Step 3: Dark Mode Integration
Connect the toggle to dark mode with a few lines of JavaScript:
``javascript
document.getElementById('dark-mode').addEventListener('change', (e) => {
document.documentElement.classList.toggle('dark', e.target.checked);
});
``
Then define CSS custom properties for light/dark themes and override them with html.dark { ... }.
Explore 100+ toggle switch designs in the UIsen toggles collection.
Frequently Asked Questions
How do I make a CSS toggle switch?
Use a hidden checkbox paired with a styled label. The label's ::after pseudo-element becomes the knob, and :checked moves it with transform: translateX(). Add transition for smooth animation. No JavaScript is needed for the toggle mechanism.
Related Articles
The Complete Guide to CSS Button Hover Effects (2026)
Learn 10+ CSS button hover effects with code examples: gradient slides, glow effects, 3D press, ripple animations, and more. Includes copy-paste code and accessibility tips.
ComparisonsBest Free UI Component Libraries in 2026 — The Definitive Guide
Compare the top free UI component libraries for 2026 including UIsen, shadcn/ui, Radix, Headless UI, and more. Includes feature comparisons, pros/cons, and use cases for each library.