CSS3 Only iOS Switch Button

Category: CSS & CSS3 , Form | March 9, 2018
Author: lluxui
Views Total: 2,075
Official Page: Go to website
Last Update: March 9, 2018
License: MIT

Preview:

CSS3 Only iOS Switch Button

Description:

Yet another CSS/CSS3 solution to creating an iOS-style switch toggle button animated with CSS3 transforms and transitions.

How to use it:

Create a checkbox input for the switch.

<label class="switch">
  <input type="checkbox" checked>
  <span></span> 
</label>

The primary CSS/CSS3 for the switch.

label.switch {  
  text-align: left;
  width: 150px;
  height: calc(150px / 2);
  border-radius:60px;    
  background-color:#4ed164;
  display: inline-block;
  position: relative;
  cursor: pointer;
}

label.switch > span {
  display: block;
  width: 100%;
  height: 100%;
}

label.switch > input[type="checkbox"] {
  opacity: 0;
  position: absolute;
} 

label.switch > span:before, label.switch > span:after {
  content: "";
  cursor: pointer;
  position: absolute;
}

label.switch > input[type="checkbox"]:focus ~ span {
  box-shadow: 0 0 0 4px #43b556; 
}

label.switch > input[type="checkbox"]:checked:focus ~ span {
  box-shadow: 0 0 0 4px #fff;
}

label.switch > span {
  border-radius: 60px;    
}

label.switch > span:before {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  background-color: #f1f1f1;
  border-radius: 60px;
  transition: opacity .2s ease-out .1s, transform .2s ease-out .1s;
  transform: scale(1);
  opacity: 1;
}

label.switch > span:after{
  top: 50%;
  z-index: 3;
  transition: transform .4s cubic-bezier(0.44,-0.12, 0.07, 1.15);
  width: calc(150px / 2);
  height: calc(150px / 2);
  transform: translate3d(0, -50%, 0);
  background-color: #fff;
  border-radius: 100%;
  box-shadow: 0 2px 5px rgba(0, 0, 0, .3);  
}

Animate the switch when checked.

label.switch > input[type="checkbox"]:checked ~ span:before {
  transform: scale(0);
  opacity: .7;
}

label.switch > input[type="checkbox"]:checked ~ span:after {
  transform: translate3d(100%, -50%, 0);
}

You Might Be Interested In:

Leave a Reply