Hello everyone! In this quick tutorial, let's learn how to create a custom toggle switch using HTML and CSS.
Step 1 - The HTML.
<...
For further actions, you may consider blocking this person and/or reporting abuse
Great tip!
I just did a small change to the CSS to give a transition effect to both the tick and the cross.
Hey! This looks amazing😍🤩 Thank u so much!
Nice quick tut! Since it's aimed to beginners, it would also benefit from a quick explanation of why clicking the also influences the invisible checkbox.
Oh yea I actually forgot to add that 😅 Thanks for the suggestion
Really nice! I love that you used
:checked
instead of using some JS.Don't forget to make it accessible to screen readers.
For that I would replace the label by a span. The input would be labelled somewhere else in the form. I would add
aria-hidden
on the span. That way screen readers will ignore the svgs that are not important for to understand the input.Hey, thanks! I will surely make these changes.😄
Cool example. I love these pure css solutions.
Here's mine
codepen.io/Tyutyesz/pen/VwvNbbZ
Looks nice. clean and minimal
Great article, i never tried to use css do that, alwayse use js to trigger an event, but css seems to be more accurate, thanks
Thanks!
I am wondering if you could suggest basic integration to, for example, switching themes? What would be the best approach?
Yes, we can use this toggle to switch themes using javascript. We will have to add an event listener on the checkbox to listen for the 'change' event and create a function that toggles the theme on the body. First, you have to define your dark-mode class in your CSS and the javascript will look something like this,
Is there any reason not using .checkbox {display:none} instead of .checkbox {
opacity: 0;
width: 0;
height: 0;
}?
great material and presentation. thank you!
Hey, thank u so much for pointing that out. It's actually my fault😅 I was trying different things to hide that checkbox to see what works best (like display: none, height:0 width:0, opacity:0, etc), and by mistake, I forgot to remove the extra code when writing this article😅display: none also works!.
Awesome! I made one, but without svg...
Now I will try this too!!!
Nice one like it
Thank u!
Good article, nicely done. I remember I've done something similar and even tried to make a web component from it.
I've called it switch-web-component
Nice😀
Thanks for a great example. A question, can this be done with radio as well? I see a great benefit in some radio choice lists using this technic.
Greatings from Norway.
Hey, thanks! Yes, I think we can also create a custom radio button. I've never tried it but I will try😀