Layout · 15 of 23

Toggle Switch

Smooth state transition

HTML · CSS · No dependencies · MIT

HTML

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

CSS

.switch {
  position: relative;
  display: inline-block;
  width: 50px;
  height: 28px;
}

/* Hide the checkbox but keep it functional/accessible */
.switch input {
  opacity: 0;
  width: 0;
  height: 0;
}

.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #333;
  transition: 0.4s;
  border-radius: 34px;
}

.slider:before {
  position: absolute;
  content: "";
  height: 20px;
  width: 20px;
  left: 4px;
  bottom: 4px;
  background-color: white;
  /* Overshooting cubic-bezier makes the knob feel springy */
  transition: 0.4s cubic-bezier(0.34, 1.56, 0.64, 1);
  border-radius: 50%;
}

input:checked + .slider {
  background-color: #7c5cff;
}

input:checked + .slider:before {
  transform: translateX(22px);
}