Fix Tailwind v4 @theme Token Drift and Dark-Mode Contrast
Toggling html[data-theme="dark"] leaves bg-canvas / text-ink frozen in light colors | dark:* utilities ignore manual toggle and follow OS preference | bg-signal/15 renders transparent | Dark-mode muted text & accent fail 4.5:1 WCAG AA After migrating a design system to Tailwind CSS v4 or letting a coding agent scaffold dark mode, toggling [data-theme="dark"] either leaves cards frozen bright white, makes dark:* utilities ignore your theme switch, breaks slash-opacity modifiers like bg-signal/15, or renders muddy red buttons and illegible dark-gray copy.
Four Tailwind CSS v4 architecture traps cause token drift: plain @theme resolves custom properties at :root instead of preserving runtime references via @theme inline; dark: defaults to prefers-color-scheme unless overridden with @custom-variant dark; legacy v3 space-separated RGB triplets break v4 color-mix() opacity utilities; and reusing light-mode ink/accent hex values on #0C0C0C dark surfaces plunges contrast below 4.5:1.
Copy-Paste Verified Fix
#!/usr/bin/env bash
set -euo pipefail
CSS_FILE="${1:-src/styles/global.css}"
echo "=== 1. Checking Tailwind v4 @theme inline & arbitrary hex sprawl ==="
if grep -qE '^@themes*{' "$CSS_FILE"; then
echo "WARN: Plain '@theme {' found in $CSS_FILE — use '@theme inline {' for runtime var(--*) color tokens."
fi
grep -rnE '(bg|text|border|ring|fill|stroke)-\[#([0-9a-fA-F]{3,8})\]' src/components src/pages 2>/dev/null && \
echo "FAIL: Replace arbitrary Tailwind hex classes above with semantic @theme inline tokens!" || \
echo "PASS: Zero arbitrary hardcoded hex utility classes found."
echo ""
echo "=== 2. Auditing WCAG 2.1 AA contrast across Light & Dark token pairs ==="
node -e '
const pairs = [
["Light: ink on canvas", "#111111", "#F7F7F5", 4.5],
["Light: ink-muted on surface", "#575754", "#FFFFFF", 4.5],
["Light: signal on surface", "#C83614", "#FFFFFF", 4.5],
["Light: signal-ink on signal", "#FFFFFF", "#C83614", 4.5],
["Dark: ink on canvas", "#EDEDEB", "#0C0C0C", 4.5],
["Dark: ink-muted on surface", "#9A9A95", "#141414", 4.5],
["Dark: signal on surface", "#F05A36", "#141414", 4.5],
["Dark: signal-ink on signal", "#0C0C0C", "#F05A36", 4.5],
];
const lin = (c) => {
const s = c / 255;
return s <= 0.03928 ? s / 12.92 : Math.pow((s + 0.055) / 1.055, 2.4);
};
const lum = (hex) => {
const n = parseInt(hex.slice(1), 16);
return 0.2126 * lin((n >> 16) & 255) + 0.7152 * lin((n >> 8) & 255) + 0.0722 * lin(n & 255);
};
const ratio = (a, b) => {
const [l1, l2] = [lum(a), lum(b)].sort((x, y) => y - x);
return (l1 + 0.05) / (l2 + 0.05);
};
let failed = 0;
for (const [label, fg, bg, min] of pairs) {
const r = ratio(fg, bg);
const ok = r >= min;
if (!ok) failed++;
console.log(`${ok ? "PASS" : "FAIL"} [${r.toFixed(2)}:1 >= ${min}:1] ${label} (${fg} on ${bg})`);
}
process.exit(failed > 0 ? 1 : 0);
' Before vs. After (Broken Pattern vs. Verified Fix)
@import "tailwindcss";
/* BUG 1: No @custom-variant dark -> ignores [data-theme="dark"] toggle
BUG 2: Plain @theme evaluates at :root, breaking scoped dark subtrees
BUG 3: Raw RGB triplet breaks bg-signal/15 color-mix() in Tailwind v4 */
:root { --bg-canvas: #F7F7F5; --accent-rgb: 200 54 20; --ink-muted: #575754; }
[data-theme="dark"] { --bg-canvas: #0C0C0C; /* forgot to lift --ink-muted! */ }
@theme {
--color-canvas: var(--bg-canvas);
--color-signal: rgb(var(--accent-rgb));
} @import "tailwindcss";
@custom-variant dark (&:where(.dark, .dark *, [data-theme="dark"], [data-theme="dark"] *));
:root {
color-scheme: light;
--bg-canvas: #F7F7F5; --bg-surface: #FFFFFF;
--ink-primary: #111111; --ink-secondary: #575754;
--accent-signal: #C83614; --accent-signal-ink: #FFFFFF;
}
[data-theme="dark"] {
color-scheme: dark;
--bg-canvas: #0C0C0C; --bg-surface: #141414;
--ink-primary: #EDEDEB; --ink-secondary: #9A9A95;
--accent-signal: #F05A36; --accent-signal-ink: #0C0C0C;
}
@theme inline {
--color-canvas: var(--bg-canvas); --color-surface: var(--bg-surface);
--color-ink: var(--ink-primary); --color-ink-muted: var(--ink-secondary);
--color-signal: var(--accent-signal); --color-signal-ink: var(--accent-signal-ink);
} Why this works: @theme inline emits runtime var() references directly inside utilities, @custom-variant dark synchronizes dark:* with manual toggles, full hex tokens power native color-mix() opacity modifiers, and lifted dark-mode tokens guarantee >= 4.5:1 WCAG AA contrast.
Why This Failure Happens in Real Pipelines
In Tailwind CSS v4, configuration moves out of tailwind.config.js into CSS-first @theme blocks. When you write plain @theme { --color-canvas: var(--bg-canvas); }, Tailwind emits --color-canvas: var(--bg-canvas) on :root and compiles .bg-canvas to background-color: var(--color-canvas). Under CSS custom-property inheritance, --color-canvas evaluates --bg-canvas at :root scope; if a scoped dark preview card (<section data-theme="dark">) or dynamic subtree overrides --bg-canvas, child elements still inherit :root’s already-resolved light color! Switching to @theme inline instructs Tailwind v4 to emit background-color: var(--bg-canvas) directly in every utility class so theme switches cascade dynamically at any DOM depth.
A second frequent shock during v3-to-v4 upgrades is that dark:* utilities stop responding to manual .dark or [data-theme="dark"] toggles because Tailwind v4 ignores old tailwind.config.js darkMode: "class" settings and falls back to @media (prefers-color-scheme: dark). Adding one explicit @custom-variant dark (&:where(.dark, .dark *, [data-theme="dark"], [data-theme="dark"] *)); line directly below @import "tailwindcss"; restores manual toggle control. Similarly, Tailwind v4 computes opacity modifiers like bg-signal/15 using native CSS color-mix(in oklab, var(--accent-signal) 15%, transparent), which breaks silently if your :root tokens still store legacy Tailwind v3 unframed channel triplets like 200 54 20 instead of valid hex or oklch() colors.
Finally, visual token drift ruins readability even when switching technically works: a crisp light-mode vermilion accent (#C83614 against #FFFFFF = 5.26:1 AA pass) drops to 3.72:1 against a #0C0C0C darkroom canvas, while light-mode secondary graphite (#575754 against #F7F7F5 = 6.76:1) collapses to 2.54:1 on #141414 dark cards. Dark themes require dedicated lifted luminance values—such as #F05A36 paired with dark #0C0C0C button ink (--accent-signal-ink) and #9A9A95 secondary ink (6.52:1 on #141414)—verified programmatically against WCAG 2.1 AA thresholds alongside color-scheme: light / dark.
Step-by-Step Resolution & Verification
- 01
Convert runtime CSS variable bindings from @theme to @theme inline and wire @custom-variant dark
Add @custom-variant dark (&:where(.dark, .dark *, [data-theme="dark"], [data-theme="dark"] *)); right below @import "tailwindcss"; and switch your semantic color token block to @theme inline so dark themes cascade cleanly across both root html and scoped dark containers.
- 02
Replace legacy v3 RGB triplets and tune dark-mode muted & accent luminance
Store complete CSS color strings (hex or oklch) in :root and [data-theme="dark"] so bg-signal/15 opacity modifiers compile via color-mix(), add color-scheme: light / dark, and lift dark-mode secondary ink and accent colors until every pair clears 4.5:1.
- 03
Run the token grep + contrast gate and capture light/dark Playwright screenshots
Execute audit-tailwind-v4-tokens.sh to eliminate arbitrary bg-[#...] leaks and verify exact WCAG ratios, then visually inspect both Daylight and Darkroom renders at 1440px and 390px via Playwright MCP.
bash audit-tailwind-v4-tokens.sh src/styles/global.css PASS: Zero arbitrary hardcoded hex utility classes found.
PASS [17.60:1 >= 4.5:1] Light: ink on canvas (#111111 on #F7F7F5)
PASS [7.25:1 >= 4.5:1] Light: ink-muted on surface (#575754 on #FFFFFF)
PASS [5.26:1 >= 4.5:1] Light: signal on surface (#C83614 on #FFFFFF)
PASS [6.52:1 >= 4.5:1] Dark: ink-muted on surface (#9A9A95 on #141414)
PASS [5.46:1 >= 4.5:1] Dark: signal on surface (#F05A36 on #141414) How to Prevent This Error From Recurring
Define button foreground ink as a paired semantic token (--accent-signal-ink)
Light-mode buttons often look sharpest with white text on deep vermilion, while brighter dark-mode accents achieve higher contrast with #0C0C0C dark ink—pairing text-signal-ink with bg-signal prevents unreadable white-on-orange buttons.
Ban arbitrary Tailwind hex classes in AGENTS.md and SKILL.md
Pairing Skill 32 (design-tokens-tailwind-v4-skill) with a CI grep check guarantees coding agents map every new Figma frame strictly to semantic utilities.
Never rely solely on CSS filter: invert() for dark mode
Inverting an entire page destroys brand color accuracy, turns photography into film negatives, and produces harsh pure-black glare—explicit semantic token tables stay clean and accessible.
Troubleshooting FAQs
- When should I use plain @theme versus @theme inline in Tailwind CSS v4?
- Use plain @theme for static build-time design primitives that never change at runtime (such as font stacks or spacing scales), and always use @theme inline whenever a utility token references another runtime CSS variable like var(--bg-canvas) that flips under [data-theme="dark"].
- Why did bg-signal/20 stop working after migrating from Tailwind v3 to v4?
- Tailwind v3 relied on rgb(var(--color) / <alpha-value>) with space-separated numbers like 200 54 20. Tailwind v4 uses native CSS color-mix(in oklab, ...), which requires valid complete color strings like #C83614 or oklch(0.55 0.19 32).
- Why do I need @custom-variant dark if I already flip semantic CSS variables under [data-theme="dark"]?
- Semantic CSS variables automatically flip bg-canvas, bg-surface, and text-ink without any dark: prefixes, but third-party components or rare one-off borders/shadows using dark:* classes will follow OS prefers-color-scheme instead of your manual toggle unless @custom-variant dark is registered.
- What WCAG contrast ratio is required for body text versus borders and large display headings?
- WCAG 2.1 AA requires at least 4.5:1 for normal body text and UI labels under 18pt (or 14pt bold), and at least 3.0:1 for large display headings (>= 24px regular / 18.66px bold) and non-text UI boundaries like active input borders.
- How do I stop a white flash (FOUC) before dark mode loads on static Astro or Next.js sites?
- Place a tiny synchronous inline <script is:inline> inside <head> before stylesheets paint that reads localStorage.theme (falling back to matchMedia prefers-color-scheme) and sets document.documentElement.dataset.theme = "dark" immediately.