Back
Discover how to create a dynamic toggle switch that brings vivid colors to life with each state change, enhancing user interaction.
<div class="toggle-container">
<input type="checkbox" id="toggle-switch" class="toggle-switch">
<label for="toggle-switch" class="toggle-label">
<span class="toggle-ball"></span>
</label>
</div>
.toggle-container {
display: inline-block;
position: relative;
width: 60px;
height: 30px;
}
Next, the toggle-switch, our hidden checkbox, is suppressed via setting its opacity to zero and eliminating any physical presence with zero dimensions. This ensures that the actual toggle mechanism remains invisible.
.toggle-switch {
opacity: 0;
width: 0;
height: 0;
}
The toggle-label, which resembles the switch itself, is given positional and shape properties. It undergoes a change in background color upon the checkbox's checked state, transitioning smoothly for a visually appealing change, from gray to green.
.toggle-label {
position: absolute;
cursor: pointer;
background-color: #cccccc;
border-radius: 30px;
width: 100%;
height: 100%;
transition: background-color 0.3s;
}
Finally, the transition of the toggle-ball, which simulates the sliding mechanism, involves a simple transform movement from its initial state on the left to the right. It provides visual feedback when the toggle is engaged with a smooth motion animation.
.toggle-ball {
position: absolute;
top: 5px;
left: 5px;
height: 20px;
width: 20px;
background-color: #ffffff;
border-radius: 50%;
transition: transform 0.3s;
}
.toggle-switch:checked + .toggle-label {
background-color: #4CAF50;
}
.toggle-switch:checked + .toggle-label .toggle-ball {
transform: translateX(30px);
}
<div class="toggle-container">
<input type="checkbox" id="toggle-switch" class="toggle-switch">
<label for="toggle-switch" class="toggle-label">
<span class="toggle-ball"></span>
</label>
</div>
<style>
.toggle-container {
display: inline-block;
position: relative;
width: 60px;
height: 30px;
}
.toggle-switch {
opacity: 0;
width: 0;
height: 0;
}
.toggle-label {
position: absolute;
cursor: pointer;
background-color: #cccccc;
border-radius: 30px;
width: 100%;
height: 100%;
transition: background-color 0.3s;
}
.toggle-ball {
position: absolute;
top: 5px;
left: 5px;
height: 20px;
width: 20px;
background-color: #ffffff;
border-radius: 50%;
transition: transform 0.3s;
}
.toggle-switch:checked + .toggle-label {
background-color: #4CAF50;
}
.toggle-switch:checked + .toggle-label .toggle-ball {
transform: translateX(30px);
}
</style>
Thank you for reading this article.
Comments
No comments yet. Be the first to comment!