Dark mode & variants

@custom-variant, data-* and aria-* variants, and a theme switch that respects the system.

What it is

A variant is a condition in front of a utility: hover:, md:, dark:. Out of the box dark: follows the device's setting; to let visitors choose, this site redefines it with @custom-variant to follow a data-theme attribute on <html>, keeping the device setting as the fallback when JavaScript is off. A tiny script in <head> sets the attribute before anything is drawn, so a dark-mode visitor never sees a white flash. The same idea, styling from state the markup already has, covers aria-pressed:, data-[state=open]:, user-invalid:, has-[:checked]:, and group-/peer- variants that react to a parent or a sibling.

When to use it

  • A theme switch: offer System, Light and Dark, and remember the choice
  • Style from ARIA and data attributes, so state and appearance can't drift apart
  • group-* and peer-* instead of JavaScript for hover reveals and form hints
Official docs ↗

1. A theme switch for the whole site

The same switch sits at the bottom of the sidebar on every page. System keeps following your device, even when it changes while the page is open.

2. dark: and the token approach

With dark: variants

Each colour written twice: bg-white dark:bg-zinc-900. Fine for one-offs.

With tokens

Written once: bg-surface. The token changes under it, which is how this site does it.

3. State variants

  • aria-pressed: a toggle button

    aria-pressed:bg-accent aria-pressed:text-white
  • data-[state=open]: a disclosure

    The state lives in a data attribute; the styles read it.

    group group-data-[state=open]:rotate-180 data-[state=closed]:hidden
  • user-invalid: + peer: a form hint

    peer peer-user-invalid:block hidden
  • has-[:checked]: a selectable card

    has-[:checked]:border-accent has-[:checked]:bg-surface
  • group-hover: reveal on hover or focus

    group group-hover:opacity-100 group-focus-visible:opacity-100
Show code · node_modules/@djmiskey/lab-tokens/theme.ts
// The theme switch: "system" (follow the device), "light" or "dark".
// <html data-theme> always holds the resolved theme, so CSS only has to look
// at one attribute; <html data-theme-choice> holds the choice.
//
// The choice is kept in a cookie on djmiskey.com, so every lab
// (obs.djmiskey.com, motion.djmiskey.com…) shares it: pick Dark once and they
// all follow. Elsewhere (localhost, *.vercel.app) it falls back to
// localStorage on that site.
export type ThemeChoice = "system" | "light" | "dark";
export const THEME_KEY = "theme";
export const SHARED_DOMAIN = "djmiskey.com";

/**
 * Runs inline in <head>, before the page is drawn, so the first paint already
 * has the right colours (no flash of the wrong theme). Kept tiny and
 * dependency-free; storage can be blocked, hence the try.
 */
export const THEME_SCRIPT = `(function(){try{var m=document.cookie.match(/(?:^|; )${THEME_KEY}=(system|light|dark)/),c=m?m[1]:localStorage.getItem("${THEME_KEY}")||"system",d=c==="dark"||(c==="system"&&matchMedia("(prefers-color-scheme: dark)").matches),e=document.documentElement;e.dataset.theme=d?"dark":"light";e.dataset.themeChoice=c}catch(x){}})()`;

export function resolve(choice: ThemeChoice, systemDark: boolean): "light" | "dark" {
  return choice === "system" ? (systemDark ? "dark" : "light") : choice;
}

/** The cookie that shares a choice across the labs, or null off the shared domain. */
export function themeCookie(choice: ThemeChoice, hostname: string): string | null {
  const shared = hostname === SHARED_DOMAIN || hostname.endsWith(`.${SHARED_DOMAIN}`);
  if (!shared) return null;
  return `${THEME_KEY}=${choice}; Domain=${SHARED_DOMAIN}; Path=/; Max-Age=31536000; SameSite=Lax; Secure`;
}

/** Applies a choice to the page now. */
export function applyChoice(choice: ThemeChoice) {
  const root = document.documentElement;
  root.dataset.theme = resolve(choice, matchMedia("(prefers-color-scheme: dark)").matches);
  root.dataset.themeChoice = choice;
}

/** Remembers a choice: in the shared cookie on djmiskey.com, and in localStorage. */
export function storeChoice(choice: ThemeChoice) {
  const cookie = themeCookie(choice, location.hostname);
  if (cookie) document.cookie = cookie;
  try { localStorage.setItem(THEME_KEY, choice); } catch { /* storage blocked: works for this visit only */ }
}
Show code · node_modules/@djmiskey/lab-tokens/ThemeSwitch.tsx
"use client";

import { useEffect, useSyncExternalStore } from "react";
import { applyChoice, storeChoice, type ThemeChoice } from "./theme";

const CHOICES: { id: ThemeChoice; label: string }[] = [
  { id: "system", label: "System" },
  { id: "light", label: "Light" },
  { id: "dark", label: "Dark" },
];

// The choice lives on <html data-theme-choice>; components read it from
// there (and re-render when it changes) instead of keeping a copy.
function subscribe(onChange: () => void) {
  const observer = new MutationObserver(onChange);
  observer.observe(document.documentElement, { attributes: true, attributeFilter: ["data-theme-choice"] });
  return () => observer.disconnect();
}
const current = () => (document.documentElement.dataset.themeChoice as ThemeChoice | undefined) ?? "system";

// System / Light / Dark, for the whole site. The inline script in <head>
// already applied the stored choice before the first paint; this stores
// changes and follows the device while "System" is chosen.
export function ThemeSwitch() {
  // null on the server: no button shows as pressed until the page knows.
  const choice = useSyncExternalStore(subscribe, current, () => null);

  useEffect(() => {
    if (choice !== "system") return;
    const media = matchMedia("(prefers-color-scheme: dark)");
    const follow = () => applyChoice("system");
    media.addEventListener("change", follow);
    return () => media.removeEventListener("change", follow);
  }, [choice]);

  const pick = (c: ThemeChoice) => {
    applyChoice(c);
    storeChoice(c);
  };

  return (
    <div className="flex w-full gap-1 rounded-lg border border-line p-0.5" role="group" aria-label="Colour theme">
      {CHOICES.map((c) => (
        <button
          key={c.id}
          type="button"
          aria-pressed={choice === c.id}
          onClick={() => pick(c.id)}
          className="flex-1 cursor-pointer rounded-md px-2 py-1 text-xs text-muted hover:text-fg aria-pressed:bg-accent aria-pressed:font-semibold aria-pressed:text-white"
        >
          {c.label}
        </button>
      ))}
    </div>
  );
}
Show code · node_modules/@djmiskey/lab-tokens/tokens.css
/* The shared tokens of the djmiskey.com labs, as plain CSS custom properties:
   no build step needed, so a lab without Tailwind can use them too.

   Each lab supplies its own accent, the one colour that tells the labs apart:
     :root {
       --lab-accent: #0369a1;          buttons and highlights; white text on it ≥ 4.5:1
       --lab-accent-dark: #0369a1;     optional, if dark mode needs a different one
       --lab-accent-ink: #075985;      accent-coloured text, ≥ 4.5:1 on --bg, --surface, --code
       --lab-accent-ink-dark: #38bdf8; the same, on the dark backgrounds
     }

   The theme: <html data-theme="light|dark"> decides (set before the first
   paint by the script in theme.ts); without it (no JavaScript), the device
   setting does. The dark values appear twice because a selector can't sit
   both inside and outside a media query. */
:root {
  --bg: #f7f7f5;
  --surface: #ffffff;
  --line: #e3e2de;
  --fg: #1d1d1b;
  --muted: #64625d;
  --code: #f1f0ec;
  --danger: #c0362c;
  --accent: var(--lab-accent);
  --accent-ink: var(--lab-accent-ink);
  color-scheme: light;
}
:root[data-theme="dark"] {
  --bg: #131312;
  --surface: #1c1c1a;
  --line: #2f2e2b;
  --fg: #ecebe7;
  --muted: #a09e97;
  --code: #232321;
  --danger: #ff7b6e;
  --accent: var(--lab-accent-dark, var(--lab-accent));
  --accent-ink: var(--lab-accent-ink-dark);
  color-scheme: dark;
}
@media (prefers-color-scheme: dark) {
  :root:not([data-theme]) {
    --bg: #131312;
    --surface: #1c1c1a;
    --line: #2f2e2b;
    --fg: #ecebe7;
    --muted: #a09e97;
    --code: #232321;
    --danger: #ff7b6e;
    --accent: var(--lab-accent-dark, var(--lab-accent));
    --accent-ink: var(--lab-accent-ink-dark);
    color-scheme: dark;
  }
}
Show code · node_modules/@djmiskey/lab-tokens/tailwind.css
/* The shared tokens for a Tailwind v4 lab. Import it after Tailwind:
     @import "tailwindcss";
     @import "@djmiskey/lab-tokens/tailwind.css";
   then set the lab's accent (see tokens.css). */
@import "./tokens.css";

/* The theme switch's classes live in this package; tell Tailwind to scan it. */
@source "./ThemeSwitch.tsx";

/* dark: follows the theme switch, with the same no-JavaScript fallback.
   @slot is where the utility's styles go. */
@custom-variant dark {
  &:where([data-theme="dark"], [data-theme="dark"] *) {
    @slot;
  }
  @media (prefers-color-scheme: dark) {
    &:where(:root:not([data-theme]), :root:not([data-theme]) *) {
      @slot;
    }
  }
}

/* Components use the tokens through these colours (bg-surface, text-muted,
   border-line…), so dark mode needs no dark: variants. */
@theme inline {
  --color-bg: var(--bg);
  --color-surface: var(--surface);
  --color-line: var(--line);
  --color-fg: var(--fg);
  --color-muted: var(--muted);
  --color-accent: var(--accent);
  --color-accent-ink: var(--accent-ink);
  --color-code: var(--code);
  --color-danger: var(--danger);
  --font-sans: system-ui, -apple-system, "Segoe UI", sans-serif;
  --font-mono: ui-monospace, SFMono-Regular, Menlo, monospace;
}

/* Fluid type and spacing: each grows in a straight line from 320 to 960px
   wide, then holds. cqi measures the nearest container, or the viewport when
   there isn't one. (Generated by fluidClamp() in the labs hub, djmiskey.com/tailwind/fluid.) */
@theme {
  --text-fluid-sm: clamp(0.875rem, 0.8125rem + 0.3125cqi, 1rem);
  --text-fluid-base: clamp(1rem, 0.9375rem + 0.3125cqi, 1.125rem);
  --text-fluid-lg: clamp(1.125rem, 0.9375rem + 0.9375cqi, 1.5rem);
  --text-fluid-lg--line-height: 1.4;
  --text-fluid-2xl: clamp(1.375rem, 1.0625rem + 1.5625cqi, 2rem);
  --text-fluid-2xl--line-height: 1.25;
  --text-fluid-4xl: clamp(1.75rem, 1rem + 3.75cqi, 3.25rem);
  --text-fluid-4xl--line-height: 1.1;
  --spacing-fluid-sm: clamp(0.75rem, 0.375rem + 1.875cqi, 1.5rem);
  --spacing-fluid-lg: clamp(1.25rem, -0.125rem + 6.875cqi, 4rem);
}

/* Element defaults for the explanatory text on every lab page. */
@layer base {
  body { @apply bg-bg font-sans text-[15px] leading-relaxed text-fg; }
  a { @apply text-accent-ink; }
  /* Links inside running text need more than colour to stand out (WCAG 1.4.1). */
  article :is(p, li) a { @apply underline underline-offset-2; }
  h1 { @apply mb-1.5 text-fluid-2xl font-bold; }
  h2 { @apply mb-2.5 text-[1.05rem] font-bold; }
  h3 { @apply mt-5 mb-2 text-[0.95rem] font-bold; }
  p { @apply my-3 first:mt-0; }
  ul, ol { @apply my-0 pl-5; }
  ol { @apply list-decimal; }
  ul { @apply list-disc; }
  code { @apply rounded bg-code px-1.5 py-0.5 font-mono text-[0.9em]; }
  input:not([type="checkbox"]):not([type="range"]):not([type="color"]), select {
    @apply min-w-0 rounded-md border border-line bg-bg px-2 py-1.5 text-fg focus:outline-2 focus:outline-accent;
  }
  input[type="range"], input[type="checkbox"] { @apply accent-accent; }
}