AI CSS Animations

Bootstrap Style Toggle Switch

The Bootstrap 5 form-switch look without the framework: a slim outlined track, a gray knob that turns white on a filled track, and the soft glow ring on focus. Sized in em to sit on a line of text.

Also known as: bootstrap switch css, bootstrap form switch, form-switch checkbox.

HTML

<label class="tgl-bootstrap">
  <input type="checkbox" role="switch">
  <span class="tgl-bootstrap-track" aria-hidden="true"></span>
  Remember this device
</label>

CSS

.tgl-bootstrap {
  --c: var(--tgl-color, #3b82f6);
  font-size: var(--tgl-size, 24px);
  position: relative;
  display: inline-flex;
  vertical-align: middle;
  cursor: pointer;
  -webkit-tap-highlight-color: transparent;
  align-items: center;
  gap: 0.5em;
  font-family: system-ui, sans-serif;
  white-space: nowrap;
}
.tgl-bootstrap input {
  position: absolute;
  inset: 0;
  width: 100%;
  height: 100%;
  margin: 0;
  opacity: 0;
  cursor: pointer;
  z-index: 1;
}
.tgl-bootstrap-track {
  position: relative;
  width: 2em;
  height: 1em;
  border: 1px solid color-mix(in srgb, currentColor 28%, transparent);
  border-radius: 1em;
  transition: background-color 0.15s ease-in-out, border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
}
.tgl-bootstrap-track::after {
  content: "";
  position: absolute;
  top: calc(50% - 0.375em);
  left: 0.1em;
  width: 0.75em;
  height: 0.75em;
  border-radius: 50%;
  background: color-mix(in srgb, currentColor 28%, transparent);
  transition: transform 0.15s ease-in-out, background-color 0.15s ease-in-out;
}
.tgl-bootstrap input:checked + .tgl-bootstrap-track {
  border-color: var(--c);
  background: var(--c);
}
.tgl-bootstrap input:checked + .tgl-bootstrap-track::after {
  background: #fff;
  transform: translateX(calc(1.05em - 2px));
}
.tgl-bootstrap input:focus-visible + .tgl-bootstrap-track {
  border-color: color-mix(in srgb, var(--c) 55%, transparent);
  box-shadow: 0 0 0 0.25em color-mix(in srgb, var(--c) 25%, transparent);
}
.tgl-bootstrap input:focus-visible:not(:checked) + .tgl-bootstrap-track::after { background: color-mix(in srgb, var(--c) 55%, transparent); }

@media (prefers-reduced-motion: reduce) {
  .tgl-bootstrap, .tgl-bootstrap *, .tgl-bootstrap::before, .tgl-bootstrap::after, .tgl-bootstrap *::before, .tgl-bootstrap *::after {
    animation-duration: 0.01ms !important;
    animation-iteration-count: 1 !important;
    transition-duration: 0.01ms !important;
  }
}

Customizing this snippet

  • Color: set --tgl-color on the element or a parent. Currently previewing #3b82f6.
  • Size: set --tgl-size. Every other dimension is in em, so the whole thing scales together. Currently previewing 24px.
  • Speed: change the duration on the transition or animation shorthand. Staggered delays are relative, so they keep their rhythm.
  • Reduced motion: the rule at the end of the CSS turns the motion off for people who asked their OS for less of it. Keep it.

Similar toggle switches