Toggle Switcher using CSS
A toggle switcher is a type of UI component that allows users to switch between two states, such as on`` and off`.
HTML
<input type="checkbox" id="toggle" class="offscreen" />
<label for="toggle" class="switch"></label>
CSS
.switch {
position: relative;
display: inline-block;
width: 40px;
height: 20px;
background-color: rgba(0, 0, 0, 0.25);
border-radius: 20px;
transition: all 0.3s;
}
.switch::after {
content: '';
position: absolute;
width: 18px;
height: 18px;
border-radius: 18px;
background-color: white;
top: 1px;
left: 1px;
transition: all 0.3s;
}
input[type='checkbox']:checked + .switch::after {
transform: translateX(20px);
}
input[type='checkbox']:checked + .switch {
background-color: #7983ff;
}
.offscreen {
position: absolute;
left: -9999px;
}
In the above code snippet, we are using the input element with the type attribute set to checkbox to create a toggle switcher. We are using the :checked pseudo-class to style the switcher when it is checked. The + selector is used to select the adjacent sibling of the input element.
Demo
Conclusion
In this post, we learned how to create a toggle switcher using only CSS. You can customize the switcher by changing the colors, sizes, and animations to match your design requirements.