Sun and moon theme toggle

CSS Observer·16h ago
body {
  margin: 0;
  min-height: 100vh;
  display: grid;
  place-items: center;
  background: #e9e7e1;
  font: 15px/1.45 system-ui, sans-serif;
  transition: background 0.4s;
}

body:has([aria-pressed="true"]) {
  background: #101114;
}

.settings {
  --bg: #ffffff;
  --ink: #17181c;
  --muted: #6b6e78;
  --line: #e4e2dc;
  --bar: #e9e7e1;

  width: min(360px, 100% - 32px);
  padding: 22px;
  border: 1px solid var(--line);
  border-radius: 18px;
  background: var(--bg);
  color: var(--ink);
  box-shadow: 0 20px 50px -25px rgb(0 0 0 / 0.35);
  transition: background 0.4s, color 0.4s, border-color 0.4s;
}

.settings:has([aria-pressed="true"]) {
  --bg: #1a1b20;
  --ink: #f1f1f3;
  --muted: #8d909b;
  --line: #2b2d34;
  --bar: #2b2d34;
}

.settings__row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 16px;
}

.settings__label {
  margin: 0;
  font-weight: 600;
}

.settings__hint {
  margin: 2px 0 0;
  color: var(--muted);
  font-size: 0.85rem;
}

.settings__preview {
  display: grid;
  gap: 8px;
  margin-top: 20px;
  padding: 16px;
  border-radius: 12px;
  background: color-mix(in srgb, var(--bar) 45%, transparent);
}

.settings__preview span {
  height: 10px;
  border-radius: 99px;
  background: var(--bar);
}

.settings__preview span:nth-child(1) { width: 45%; }
.settings__preview span:nth-child(3) { width: 70%; }

.theme-toggle {
  display: grid;
  place-items: center;
  width: 48px;
  height: 48px;
  padding: 0;
  border: 1px solid var(--line);
  border-radius: 50%;
  background: transparent;
  color: var(--ink);
  cursor: pointer;
}

.theme-toggle:focus-visible {
  outline: 2px solid var(--ink);
  outline-offset: 3px;
}

.theme-toggle svg * {
  transform-box: view-box;
  transform-origin: 12px 12px;
  transition: transform 0.5s cubic-bezier(0.5, 1.4, 0.4, 1), opacity 0.3s;
}

[aria-pressed="true"] .theme-toggle__core {
  transform: scale(1.7);
}

[aria-pressed="true"] .theme-toggle__cut {
  transform: translateX(-8px);
}

[aria-pressed="true"] .theme-toggle__rays {
  transform: rotate(-45deg) scale(0.4);
  opacity: 0;
}

@media (prefers-reduced-motion: reduce) {
  .theme-toggle svg *,
  .settings,
  body {
    transition: none;
  }
}

Usage

The button flips aria-pressed; the CSS does the rest. The crescent is an SVG mask circle sliding over the sun. Theme colors are custom properties on .settings, swapped with :has([aria-pressed="true"]).