How to create a switch with CSS

By
César Álvarez's picture
César Álvarez
· 05/10/2016

Nowadays it's more common to find fully customized form elements that enhance the user experience.

In this article we will see how to turn a typical checkbox into a switch that is much more modern and visually appealing.

 

Let's see an example of how this switch would be used in the typical options in a user area:

 

    Publish my email address

 

    Receive newsletter

 

    Receive email notifications

 

First we need to define the html. We are going to use the labels and input tags of a typical checkbox and an extra div that will serve to do the trick with css.

HTML

  1. <label class="switch">
  2.   <input type="checkbox">
  3.   <div class="slider round"></div>
  4. </label>

 

Now let's go with the css:

CSS

  1. /* Format the label that will serve as container */
  2. .switch {
  3. position: relative;
  4. display: inline-block;
  5. width: 60px;
  6. height: 34px;
  7. }
  8.  
  9. /* Hide the html checkbox */
  10. .switch input {
  11. display:none;
  12. }
  13.  
  14. /* Format the switch box on which the control knob or slider will slide */
  15. .slider {
  16. position: absolute;
  17. cursor: pointer;
  18. top: 0;
  19. left: 0;
  20. right: 0;
  21. bottom: 0;
  22. background-color: #ccc;
  23. -webkit-transition: .4s;
  24. transition: .4s;
  25. }
  26.  
  27. /* Depict the control knob or slider using the pseudo-selector before */
  28. .slider:before {
  29. position: absolute;
  30. content: "";
  31. height: 26px;
  32. width: 26px;
  33. left: 4px;
  34. bottom: 4px;
  35. background-color: white;
  36. -webkit-transition: .4s;
  37. transition: .4s;
  38. }
  39.  
  40. /* We change the background color when the checkbox is activated */
  41. input:checked + .slider {
  42. background-color: #E27AD8;
  43. }
  44.  
  45. /* We slide the slider to the right when the checkbox is activated */
  46. input:checked + .slider:before {
  47. -webkit-transform: translateX(26px);
  48. -ms-transform: translateX(26px);
  49. transform: translateX(26px);
  50. }
  51.  
  52. /* We apply a rounded edge effect to the slider and to the bottom of the slide */
  53. .slider.round {
  54. border-radius: 34px;
  55. }
  56.  
  57. .slider.round:before {
  58. border-radius: 50%;
  59. }

That's all folks! Now we know how to create a toggle switch or switch with css. Easy, fast and for the whole family!

Main photo: Pierre Chatel
Share 

Related works

Platform for online claims
Fun musical spanish

How can we help?Get in touch