Step by step, pure CSS animated toggle switch

For me, subtle interaction animations can be a sweet touch and can breathe life into static looking page. For a recent project, I was asked to build some fancy toggle switches as part of a form, the result turned out fairly nicely so I thought I’d share a quick how to of how I styled the switches with CSS and implemented animation without using javascript. Scroll down for a live demo of each step including the final toggle switch.

  1. Create an input with an associated label – this is semantically correct and valid HTML
  2. Style the label with height and background colour, make position: relative as we will need this for absolutely positioning its children.
  3. Round the label corners and hide the label font, change the cursor to pointer to indicate to mouse users that an interaction is available.
  4. Use an :after pseudo element for the circular part of the toggle switch. Position absolute into the off position.
  5. Make use of the :checked selector and + sibling selector to target the label when the input is checked. Here the background colour is changed.
  6. Similarly, target the :after element to move it to the right, change the colour and change the shadow when the input is checked.
  7. 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.

Pure CSS animated toggle switch demo