Real spring physics in CSS: the knob overshoots and settles, and the dot inside it rides a looser spring, so it wobbles after landing. Both curves are linear() easings with a cubic-bezier fallback.
Also known as: bouncy toggle switch, spring animation switch css, elastic toggle css.
<label class="tgl-spring">
<input type="checkbox" role="switch" aria-label="Haptics">
<span class="tgl-spring-track" aria-hidden="true">
<span class="tgl-spring-knob"></span>
<span class="tgl-spring-dot"></span>
</span>
</label>.tgl-spring {
--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-spring input {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
margin: 0;
opacity: 0;
cursor: pointer;
z-index: 1;
}
.tgl-spring-track {
position: relative;
display: block;
width: 3.8em;
height: 2em;
border-radius: 1em;
background: color-mix(in srgb, currentColor 13%, transparent);
transition: background-color 0.3s ease;
}
.tgl-spring-knob {
position: absolute;
top: 0.25em;
left: 0.25em;
width: 1.5em;
height: 1.5em;
border-radius: 50%;
background: #fff;
box-shadow: 0 0.1em 0.3em rgb(0 0 0 / 0.22);
transition: transform 0.45s cubic-bezier(0.34, 1.4, 0.64, 1);
transition: transform 0.55s linear(0, 0.077, 0.256, 0.474, 0.685, 0.863, 0.993, 1.076, 1.117, 1.126, 1.114, 1.09, 1.062, 1.036, 1.015, 0.999, 0.989, 0.985, 0.984, 0.986, 0.989, 0.993, 1);
}
/* the dot rides a looser spring than the knob, so it lags and wobbles */
.tgl-spring-dot {
position: absolute;
top: 0.8em;
left: 0.8em;
width: 0.4em;
height: 0.4em;
border-radius: 50%;
background: #cbd5e1;
transition: transform 0.7s cubic-bezier(0.3, 1.8, 0.5, 1), background-color 0.3s ease;
transition: transform 1s linear(0, 0.177, 0.565, 0.962, 1.233, 1.332, 1.287, 1.163, 1.028, 0.931, 0.89, 0.9, 0.94, 0.986, 1.02, 1.036, 1.034, 1.022, 1.007, 0.994, 0.988, 0.988, 0.992, 0.997, 1.001, 1.004, 1), background-color 0.3s ease;
}
.tgl-spring input:checked + .tgl-spring-track { background: var(--c); }
.tgl-spring input:checked + .tgl-spring-track .tgl-spring-knob { transform: translateX(1.8em); }
.tgl-spring input:checked + .tgl-spring-track .tgl-spring-dot {
background: var(--c);
transform: translateX(1.8em);
}
.tgl-spring input:focus-visible + .tgl-spring-track {
outline: 2px solid var(--c);
outline-offset: 2px;
}
@media (prefers-reduced-motion: reduce) {
.tgl-spring, .tgl-spring *, .tgl-spring::before, .tgl-spring::after, .tgl-spring *::before, .tgl-spring *::after {
animation-duration: 0.01ms !important;
animation-iteration-count: 1 !important;
transition-duration: 0.01ms !important;
}
}--tgl-color on the element or a parent.
Currently previewing #3b82f6.--tgl-size. Every other dimension is in
em, so the whole thing scales together. Currently previewing 24px.transition or animation
shorthand. Staggered delays are relative, so they keep their rhythm.