Let’s switch it up!
For a recent project I thought I’d use Materialize CSS and after working with it, determined that, while it’s a good library, it wasn’t for my project. However, I really liked the switch element they designed so I decided to remake it myself in CSS.
Doing so required I go into areas in CSS I’d never gone before, namely, pseudoelements. By manipulating ::before and ::after, I can make a functional switch out of a checkbox.
Below is the final product. It’s a switch that toggles from off to on, and turns grey and unusable when disabled.
We’re going to begin with the humble checkbox and wrap it in a label, as we should so that when the user clicks on the label, it will toggle the checkbox
For accessibility purposes you should always use labels in conjunction with form elements.
To ensure our CSS doesn’t affect other checkboxes on our site, we’ll give the label a class, and modify that class and its descendents as we continue.