AI CSS Animations

Pixel Art Toggle Switch

An 8-bit switch drawn in square pixels: box-shadow borders leave the corners notched, and the knob hops across in four steps() instead of sliding, like a menu toggle in an old console game.

Also known as: 8 bit toggle switch, pixel game switch css, retro game toggle.

HTML

<label class="tgl-pixel">
  <input type="checkbox" role="switch" aria-label="Sound effects">
  <span class="tgl-pixel-track" aria-hidden="true"></span>
</label>

CSS

.tgl-pixel {
  --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;
  padding: 0.2em;
}
.tgl-pixel input {
  position: absolute;
  inset: 0;
  width: 100%;
  height: 100%;
  margin: 0;
  opacity: 0;
  cursor: pointer;
  z-index: 1;
}
/* one pixel is 0.2em: the track is 22 by 10 pixels */
.tgl-pixel-track {
  position: relative;
  display: block;
  width: 4.4em;
  height: 2em;
  background: color-mix(in srgb, currentColor 14%, transparent);
  box-shadow:
    0 -0.2em 0 currentColor,
    0 0.2em 0 currentColor,
    -0.2em 0 0 currentColor,
    0.2em 0 0 currentColor;
}
.tgl-pixel-track::before {
  content: "";
  position: absolute;
  top: 0.4em;
  left: 0.4em;
  width: 1.2em;
  height: 1.2em;
  background: #fff;
  box-shadow:
    inset -0.2em -0.2em 0 #b8c0cc,
    0 -0.2em 0 currentColor,
    0 0.2em 0 currentColor,
    -0.2em 0 0 currentColor,
    0.2em 0 0 currentColor;
  transition: transform 0.32s steps(4, jump-end);
}
.tgl-pixel input:checked + .tgl-pixel-track {
  background: var(--c);
  box-shadow:
    inset 0.2em 0.2em 0 rgb(255 255 255 / 0.3),
    0 -0.2em 0 currentColor,
    0 0.2em 0 currentColor,
    -0.2em 0 0 currentColor,
    0.2em 0 0 currentColor;
}
.tgl-pixel input:checked + .tgl-pixel-track::before { transform: translateX(2.4em); }
.tgl-pixel input:focus-visible + .tgl-pixel-track {
  outline: 0.2em dashed var(--c);
  outline-offset: 0.4em;
}

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