Gaurav
Posted on March 5, 2021
Hello everyone! In this quick tutorial, let's learn how to create a custom toggle switch using HTML and CSS.
Step 1 - The HTML.
<label class="switch">
<input type="checkbox" class="checkbox">
<span class="toggle-thumb">
<svg xmlns="http://www.w3.org/2000/svg" width="36" height="36" viewBox="0 0 24 24" style="fill:#4ADE80;transform:;-ms-filter:"><path d="M10 15.586L6.707 12.293 5.293 13.707 10 18.414 19.707 8.707 18.293 7.293z"></path></svg>
<svg xmlns="http://www.w3.org/2000/svg" width="36" height="36" viewBox="0 0 24 24" style="fill:#F87171;transform:;-ms-filter:"><path d="M16.192 6.344L11.949 10.586 7.707 6.344 6.293 7.758 10.535 12 6.293 16.242 7.707 17.656 11.949 13.414 16.192 17.656 17.606 16.242 13.364 12 17.606 7.758z"></path></svg>
</span>
</label>
Here, the label with the class 'switch' is like the main container of our switch. The span with the class of 'toggle-thumb' is the circle part of the switch and inside this span are the 2 SVG icons that we are going to use. And We will use the checkbox to toggle the switch.
Step 2 - Basic Styles
.switch {
display: inline-block;
width: 60px;
height: 34px;
position: relative;
}
.toggle-thumb {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
display: flex;
justify-content: space-between;
align-items: center;
background-color: #475569;
border-radius: 40px;
cursor: pointer;
}
After these styles, the switch should look like this
Step 3 - Creating the toggle thumb and hiding the checkbox.
For creating the toggle thumb we need to add the '::before' pseudo-element to the 'toggle-thumb'.
.toggle-thumb:before {
content: "";
height: 26px;
width: 26px;
position: absolute;
left: 4px;
bottom: 4px;
border-radius: 50%;
background-color: #E2E8F0;
transition: .4s all ease;
}
And to hide the checkbox
.checkbox {
opacity: 0;
width: 0;
height: 0;
}
Step 4 - Adding the functionality.
To add the functionality to our switch we need to add transform to our 'toggle-thumb::before' when our checkbox is checked. So to do that,
.checkbox:checked + .toggle-thumb:before {
transform: translateX(26px);
}
That's it. Here is the demo of the switch.
Thanks ๐
Posted on March 5, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.