Simple Toggle Button With Pure HTML CSS (Free Download)
Last Updated: February 27, 2022
Welcome to a tutorial on how to create a simple custom toggle button with pure HTML and CSS. Want to create a custom toggle button without loading an entire 3rd party framework? Yes, it is possible with some clever CSS -Read on for an example!
ⓘ I have included a zip file with all the source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.
Firstly, here is the download link to the example code as promised.
QUICK NOTES
If you spot a bug, feel free to comment below. I try to answer short questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.
EXAMPLE CODE DOWNLOAD
Click here to download the source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.
Now that we have the “outer shell”, the next part is to build the “inner button” using i::before… This is basically Math, calculating the size of the “inner button” and positioning it.
PART 5) TOGGLING
toggle.css
/* (D) "ON CHECKED" */
/* (D1) CHANGE BACKGROUND COLOR */
.tog input:checked + i { background: var(--tog-on); }
/* (D2) MOVE "INNER TOGGLE BUTTON" TO RIGHT SIDE */
.tog input:checked + i::before {
left: auto;
right: var(--tog-c-offset);
}
Now that we have both the “outer container” and “inner button”, all that’s left is to deal with the toggling. For the beginners:
.tog input:checked + i { background:COLOR } In basic English, when the checkbox is checked, change the background color of the container.
.tog input:checked + i::before { POSITION } When the checkbox is checked, move the “inner button” to the right side.
This custom toggle button will work on all modern browsers. If you have to support the ancient browsers, you will have to remove and “hardcode” all the CSS variables.
Thank you for reading, and we have come to the end of this guide. I hope that it has helped you with your project, and if you have anything to share with this guide, please feel free to comment below. Good luck and happy coding!
1 thought on “Simple Toggle Button With Pure HTML CSS (Free Download)”
Rahul Jangid
Wow this is really nice, thanks for this awesome article.
Wow this is really nice, thanks for this awesome article.