Step by step, pure CSS animated toggle switch
- Create an input with an associated label – this is semantically correct and valid HTML
- Style the label with height and background colour, make
position: relativeas we will need this for absolutely positioning its children.
- Round the label corners and hide the label font, change the cursor to pointer to indicate to mouse users that an interaction is available.
- Use an
:afterpseudo element for the circular part of the toggle switch. Position absolute into the off position.
- Make use of the
+sibling selector to target the label when the input is checked. Here the background colour is changed.
- Similarly, target the :
afterelement to move it to the right, change the colour and change the shadow when the input is checked.
- Hide the input checkbox, these properties and values allow the input to remain accessible for screen readers. And, finally, add css transitions to the label elements for smooth transitions between each state.