AI CSS Animations

Fill Toggle Switch

The knob rests in a small cup of color and drags the fill behind it as it slides, so the track floods with your accent from the left. The fill is a pill moved with transform, not an animated width.

Also known as: progress fill toggle switch, slide to fill switch, trail toggle css.

HTML

<label class="tgl-fill">
  <input type="checkbox" role="switch" aria-label="Auto-save">
  <span class="tgl-fill-track" aria-hidden="true"><span class="tgl-fill-bar"></span></span>
</label>

CSS

.tgl-fill {
  --c: var(--tgl-color, #3b82f6);
  font-size: var(--tgl-size, 24px);
  position: relative;
  display: inline-block;
  vertical-align: middle;
  cursor: pointer;
  -webkit-tap-highlight-color: transparent;

}
.tgl-fill input {
  position: absolute;
  inset: 0;
  width: 100%;
  height: 100%;
  margin: 0;
  opacity: 0;
  cursor: pointer;
  z-index: 1;
}
.tgl-fill-track {
  position: relative;
  isolation: isolate;
  display: block;
  width: 3.8em;
  height: 2em;
  border-radius: 1em;
  overflow: hidden;
  background: color-mix(in srgb, currentColor 13%, transparent);
}
/* a full-width pill whose right end always hugs the knob */
.tgl-fill-bar {
  position: absolute;
  inset: 0;
  border-radius: inherit;
  background: var(--c);
  transform: translateX(-1.8em);
  transition: transform 0.45s cubic-bezier(0.65, 0, 0.35, 1);
}
.tgl-fill-track::after {
  content: "";
  position: absolute;
  top: 0.2em;
  left: 0.2em;
  width: 1.6em;
  height: 1.6em;
  border-radius: 50%;
  background: #fff;
  box-shadow: 0 0.1em 0.3em rgb(0 0 0 / 0.25);
  transition: transform 0.45s cubic-bezier(0.65, 0, 0.35, 1);
}
.tgl-fill input:checked + .tgl-fill-track .tgl-fill-bar { transform: none; }
.tgl-fill input:checked + .tgl-fill-track::after { transform: translateX(1.8em); }
.tgl-fill input:focus-visible + .tgl-fill-track {
  outline: 2px solid var(--c);
  outline-offset: 2px;
}

@media (prefers-reduced-motion: reduce) {
  .tgl-fill, .tgl-fill *, .tgl-fill::before, .tgl-fill::after, .tgl-fill *::before, .tgl-fill *::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