A switch with ON and OFF written inside the track. The words sit opposite the knob and slide out of its way as it crosses, so the state reads without color. Both labels are plain spans.
Also known as: css toggle switch with text, on off switch css, toggle switch with on off text inside.
<label class="tgl-on-off-text">
<input type="checkbox" role="switch" aria-label="Autoplay">
<span class="tgl-on-off-text-track" aria-hidden="true">
<span class="tgl-on-off-text-on">ON</span>
<span class="tgl-on-off-text-off">OFF</span>
</span>
</label>.tgl-on-off-text {
--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;
font-family: system-ui, sans-serif;
font-weight: 700;
}
.tgl-on-off-text input {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
margin: 0;
opacity: 0;
cursor: pointer;
z-index: 1;
}
.tgl-on-off-text-track {
position: relative;
display: block;
width: 4.25em;
height: 2em;
border-radius: 1em;
overflow: hidden;
background: color-mix(in srgb, currentColor 13%, transparent);
transition: background-color 0.3s ease;
}
.tgl-on-off-text-track::before {
content: "";
position: absolute;
z-index: 1;
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.35s cubic-bezier(0.3, 0.7, 0.3, 1);
}
.tgl-on-off-text-on,
.tgl-on-off-text-off {
position: absolute;
top: 0;
bottom: 0;
display: grid;
place-items: center;
width: 57.6%;
font-size: 0.6em;
letter-spacing: 0.08em;
transition: opacity 0.25s ease, transform 0.35s cubic-bezier(0.3, 0.7, 0.3, 1);
}
.tgl-on-off-text-on {
left: 0;
color: #fff;
opacity: 0;
transform: translateX(-1.2em);
}
.tgl-on-off-text-off {
right: 0;
color: color-mix(in srgb, currentColor 60%, transparent);
}
.tgl-on-off-text input:checked + .tgl-on-off-text-track { background: var(--c); }
.tgl-on-off-text input:checked + .tgl-on-off-text-track::before { transform: translateX(2.25em); }
.tgl-on-off-text input:checked + .tgl-on-off-text-track .tgl-on-off-text-on {
opacity: 1;
transform: none;
}
.tgl-on-off-text input:checked + .tgl-on-off-text-track .tgl-on-off-text-off {
opacity: 0;
transform: translateX(1.2em);
}
.tgl-on-off-text input:focus-visible + .tgl-on-off-text-track {
outline: 2px solid var(--c);
outline-offset: 2px;
}
@media (prefers-reduced-motion: reduce) {
.tgl-on-off-text, .tgl-on-off-text *, .tgl-on-off-text::before, .tgl-on-off-text::after, .tgl-on-off-text *::before, .tgl-on-off-text *::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.