A theme toggle where the sun spins away and shrinks as the moon spins in, and the button dims to night. Two icons share one grid cell and trade places with a springy rotate and scale.
Also known as: dark mode toggle icon animation, theme toggle hover css, day night icon switch.
<button class="hfx-sun-moon-swap" aria-label="Switch to dark mode"> <svg class="hfx-sun-moon-swap-sun" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M4.9 4.9l1.4 1.4M17.7 17.7l1.4 1.4M2 12h2M20 12h2M4.9 19.1l1.4-1.4M17.7 6.3l1.4-1.4"/></svg> <svg class="hfx-sun-moon-swap-moon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M20.5 14.1A8.5 8.5 0 1 1 9.9 3.5a6.6 6.6 0 0 0 10.6 10.6Z"/></svg> </button>
.hfx-sun-moon-swap {
--c: var(--hfx-color, #3b82f6);
font-size: var(--hfx-size, 16px);
position: relative;
display: grid;
place-items: center;
width: 3.5em;
height: 3.5em;
padding: 0;
border: 0;
border-radius: 50%;
cursor: pointer;
background: color-mix(in srgb, var(--c) 12%, transparent);
color: var(--c);
transition: background-color 0.4s ease, color 0.4s ease;}
.hfx-sun-moon-swap svg {
grid-area: 1 / 1;
width: 1.6em;
height: 1.6em;
transition: transform 0.55s cubic-bezier(0.34, 1.56, 0.64, 1), opacity 0.25s ease;
}
.hfx-sun-moon-swap-moon {
opacity: 0;
transform: rotate(-90deg) scale(0.3);
}
.hfx-sun-moon-swap:is(:hover, :focus-visible) {
background: color-mix(in srgb, var(--c) 30%, #0b1120);
color: #fff;
}
.hfx-sun-moon-swap:is(:hover, :focus-visible) .hfx-sun-moon-swap-sun {
opacity: 0;
transform: rotate(90deg) scale(0.3);
}
.hfx-sun-moon-swap:is(:hover, :focus-visible) .hfx-sun-moon-swap-moon {
opacity: 1;
transform: rotate(0deg) scale(1);
}
@media (prefers-reduced-motion: reduce) {
.hfx-sun-moon-swap, .hfx-sun-moon-swap *, .hfx-sun-moon-swap::before, .hfx-sun-moon-swap::after, .hfx-sun-moon-swap *::before, .hfx-sun-moon-swap *::after {
animation-duration: 0.01ms !important;
animation-iteration-count: 1 !important;
transition-duration: 0.01ms !important;
}
}--hfx-color on the element or a parent.
Currently previewing #3b82f6.--hfx-size. Every other dimension is in
em, so the whole thing scales together. Currently previewing 16px.transition or animation
shorthand. Staggered delays are relative, so they keep their rhythm.