Custom Toggle Switch
A beautifully animated, custom CSS toggle switch designed to flawlessly replace native browser checkboxes.
This snippet transforms a standard HTML checkbox into a sleek, modern toggle switch. Relying entirely on CSS pseudo-elements and the :checked state, it delivers incredibly smooth animations without a single line of JavaScript.
Code
<label class="custom-toggle">
<input type="checkbox" class="custom-toggle-input" aria-label="Toggle Switch" />
<span class="custom-toggle-slider"></span>
</label>/* Toggle switch container */
.custom-toggle {
position: relative;
display: inline-block;
width: 60px;
height: 34px;
}
/* Hide the default checkbox */
.custom-toggle-input {
opacity: 0;
width: 0;
height: 0;
}
/* Slider background */
.custom-toggle-slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #e2e8f0;
transition: background-color 0.4s;
border-radius: 34px;
box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.1);
}
/* Slider thumb */
.custom-toggle-slider:before {
position: absolute;
content: "";
height: 26px;
width: 26px;
left: 4px;
bottom: 4px;
background-color: white;
transition: transform 0.4s cubic-bezier(0.68, -0.55, 0.265, 1.55);
border-radius: 50%;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}
/* Background color when checked */
.custom-toggle-input:checked + .custom-toggle-slider {
background-color: #3b82f6;
}
/* Outline on keyboard focus */
.custom-toggle-input:focus-visible + .custom-toggle-slider {
outline: 2px solid #3b82f6;
outline-offset: 2px;
}
/* Thumb movement when checked */
.custom-toggle-input:checked + .custom-toggle-slider:before {
transform: translateX(26px);
} Implementation Points
Native <input type="checkbox"> elements suffer from inconsistent cross-browser styling and limited customization. This snippet elegantly solves this by visually hiding the default checkbox—while retaining its native functionality—and constructing a custom UI using an adjacent <span> element as the slider.
- Hiding the Native Input: Setting
opacity: 0alongside zero width and height completely removes the default checkbox from view while keeping it fully functional and accessible in the DOM. - Styling the Slider: The circular toggle “thumb” is efficiently rendered using the
::beforepseudo-element. - Fluid Animation: Applying a custom easing curve (
transition: transform 0.4s cubic-bezier(0.68, -0.55, 0.265, 1.55)) gives the thumb a highly satisfying, slightly bouncy physics effect when toggled. - Accessibility (a11y): Focus states are explicitly handled using
:focus-visible, ensuring that the custom switch receives a clear, distinct outline during keyboard navigation.
This toggle switch is highly versatile and perfect for interfaces requiring intuitive binary choices, such as application settings panels or dark mode toggles.