Toggle Switch
Projects

Toggle Switch with CSS & Dark UI

Learn how to create a “toggle switch” (on/off button) with CSS.

HTML Code

 <input class="custom" type="checkbox" id="toggle">
 <label for="toggle"><span></span></label>

CSS Code


*, *::before, *::after {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}
body {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background: #1b1e23;
}
.custom {
  visibility: hidden;
}

.custom + label {
  background: rgba(244, 238, 215, 0.25);
  display: inline;
  border-radius: 34px;
  padding: 6px;
  width: calc(34px * 2 + 6px * 2);
  transition: all 0.2s ease-in-out;
}
.custom + label span {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 34px;
  width: 34px;
  border-radius: 50%;
  background: #1b1e23;
  transition: all 0.2s ease-in-out;
}
.custom + label span:before, .custom + label span:after {
  content: "";
  display: block;
  position: absolute;
  width: 3px;
  height: 16px;
  background: #f4eed7;
  transition: all 0.2s ease-in-out;
}

.custom + label span:before {
  transform: rotateZ(45deg);
}
.custom + label span:after {
  transform: rotateZ(-45deg);
}
.custom:checked + label {
  background: #f4eed7;
}
.custom:checked + label span {
  margin-left: calc(34px);
  background: #4b9aaa;
  transform: rotateZ(-90deg);
}
.custom:checked + label span:before {
  transform: translateX(-4px) translateY(-4px) rotateZ(45deg);
  height: calc(34px / 3.4 );
}
.custom:checked + label span:after {
  transform: translateY(5px) rotateZ(-45deg);
}