Sub topic 9
Theming with CSS variables and dark mode
This chapter assumes you can read Tailwind utility classes, have run npx shadcn@latest init in a React project (covered in the CLI chapter), and know basic CSS custom properties. It uses the Tailwind v3 style of configuration. The Tailwind v4 differences are listed near the end.
Why shadcn/ui themes with variables
A copied shadcn/ui component does not contain colors like bg-zinc-900. It uses semantic class names such as bg-primary, text-muted-foreground, and border-input. Each name points to a CSS variable, and the variable's value decides the color.
This gives you two benefits:
- You can re-theme the whole application by editing one file, with no changes to component code.
- Dark mode needs no
dark:prefix on every class. The variables change, and every component follows.
The variable file
init adds a block like this to your global stylesheet, usually src/index.css or app/globals.css:
@tailwind base;
@tailwind components;
@tailwind utilities;
@layer base {
:root {
--background: 0 0% 100%;
--foreground: 222 47% 11%;
--primary: 222 47% 11%;
--primary-foreground: 210 40% 98%;
--muted: 210 40% 96%;
--muted-foreground: 215 16% 47%;
--accent: 210 40% 96%;
--accent-foreground: 222 47% 11%;
--destructive: 0 84% 60%;
--destructive-foreground: 210 40% 98%;
--border: 214 32% 91%;
--input: 214 32% 91%;
--ring: 222 47% 11%;
--radius: 0.5rem;
}
.dark {
--background: 222 47% 11%;
--foreground: 210 40% 98%;
--primary: 210 40% 98%;
--primary-foreground: 222 47% 11%;
--muted: 217 33% 17%;
--muted-foreground: 215 20% 65%;
--accent: 217 33% 17%;
--accent-foreground: 210 40% 98%;
--destructive: 0 63% 31%;
--destructive-foreground: 210 40% 98%;
--border: 217 33% 17%;
--input: 217 33% 17%;
--ring: 213 27% 84%;
}
* {
@apply border-border;
}
body {
@apply bg-background text-foreground;
}
}Three conventions are worth noting.
- Background and foreground pairs. Each surface color has a matching text color.
primaryis the fill of a primary button, andprimary-foregroundis the text on it. Keep that pairing when you add your own colors, so contrast stays predictable. - Bare HSL channels. The values are written as
222 47% 11%with nohsl()wrapper. This lets Tailwind insert an alpha value later. --radius. Components derive their corner rounding from this one variable, so changing it reshapes buttons, inputs, and cards together.
Connecting variables to Tailwind
Variables do nothing until Tailwind knows the class names. The tailwind.config.ts file maps each name to a variable and wraps it in hsl():
import type { Config } from "tailwindcss"
const config: Config = {
darkMode: ["class"],
content: ["./src/**/*.{ts,tsx}"],
theme: {
extend: {
colors: {
border: "hsl(var(--border))",
input: "hsl(var(--input))",
ring: "hsl(var(--ring))",
background: "hsl(var(--background))",
foreground: "hsl(var(--foreground))",
primary: {
DEFAULT: "hsl(var(--primary))",
foreground: "hsl(var(--primary-foreground))",
},
muted: {
DEFAULT: "hsl(var(--muted))",
foreground: "hsl(var(--muted-foreground))",
},
accent: {
DEFAULT: "hsl(var(--accent))",
foreground: "hsl(var(--accent-foreground))",
},
destructive: {
DEFAULT: "hsl(var(--destructive))",
foreground: "hsl(var(--destructive-foreground))",
},
},
borderRadius: {
lg: "var(--radius)",
md: "calc(var(--radius) - 2px)",
sm: "calc(var(--radius) - 4px)",
},
},
},
plugins: [],
}
export default configWith this mapping, bg-primary compiles to background-color: hsl(var(--primary)). The opacity form bg-primary/90, used in the Button's hover state, also works. Tailwind rewrites it to hsl(var(--primary) / 0.9), which is why the variables hold bare channels.
darkMode: ["class"] tells Tailwind to apply dark: utilities when an ancestor has the class dark. It also matches the .dark selector in the stylesheet.
How dark mode switches
Dark mode is a class on the <html> element. When it is present, the .dark block redefines the same variable names, and the cascade does the rest.
Nothing in React state is involved in the repaint. React only decides which class sits on <html>.
A theme toggle
This component stores the choice in localStorage and falls back to the operating system preference. It reads browser APIs during initialization, so it suits a client-only app such as Vite. In a server-rendered framework, use a library such as next-themes, which handles the server and client mismatch for you.
import { useEffect, useState } from "react"
type Theme = "light" | "dark"
function getInitialTheme(): Theme {
const stored = localStorage.getItem("theme")
if (stored === "light" || stored === "dark") return stored
return window.matchMedia("(prefers-color-scheme: dark)").matches
? "dark"
: "light"
}
export function ThemeToggle() {
const [theme, setTheme] = useState<Theme>(getInitialTheme)
useEffect(() => {
document.documentElement.classList.toggle("dark", theme === "dark")
localStorage.setItem("theme", theme)
}, [theme])
return (
<button
type="button"
className="rounded-md border border-input bg-background px-3 py-2 text-sm hover:bg-accent hover:text-accent-foreground"
aria-pressed={theme === "dark"}
onClick={() => setTheme(theme === "dark" ? "light" : "dark")}
>
Dark mode
</button>
)
}The aria-pressed attribute tells screen readers that this is a toggle button and whether it is on. The button text stays constant, because changing both the label and the pressed state would announce the state twice.
Avoiding the flash of the wrong theme
React runs after the page's first paint. A user who prefers dark mode would see a white flash before the effect adds the class. Fix this with a small inline script in index.html, placed in <head> before your bundle:
<script>
(function () {
var stored = localStorage.getItem("theme");
var dark =
stored === "dark" ||
(!stored && window.matchMedia("(prefers-color-scheme: dark)").matches);
document.documentElement.classList.toggle("dark", dark);
})();
</script>The script runs synchronously before the body is painted, so the first frame already has the correct class.
Creating your own theme
To change the look, edit the variable values. For a blue brand color, change only the two primary variables in each block:
:root {
--primary: 221 83% 53%;
--primary-foreground: 210 40% 98%;
--ring: 221 83% 53%;
}
.dark {
--primary: 217 91% 60%;
--primary-foreground: 222 47% 11%;
--ring: 217 91% 60%;
}Every Button, focus ring, and other primary consumer updates at once. Use a slightly lighter blue in dark mode, because saturated dark colors lose contrast against a dark background.
To add a new semantic color, such as success, make three changes:
- Define
--successand--success-foregroundin both:rootand.dark. - Add
successtotheme.extend.colorsin the Tailwind config. - Use
bg-success text-success-foregroundin your components, for example in a newcvavariant.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `bg-primary` has no effect | The color is missing from `theme.extend.colors`, or the file is outside `content` | Add the mapping and check the `content` globs |
| Colors are black or invalid | Variable written as `hsl(222, 47%, 11%)` while the config also wraps it in `hsl()` | Store bare channels such as `222 47% 11%` |
| `bg-primary/90` shows no hover change | The config uses a fixed color string instead of `hsl(var(--primary))` | Map the color through the variable |
| Dark mode never applies | `darkMode` is not set to `class`, or the class is on `<body>` while the CSS expects `<html>` | Set the class on `document.documentElement` |
| Light flash on load | The theme is applied after React mounts | Add the inline script to `<head>` |
| Text unreadable on a custom surface | A new background has no matching foreground variable | Define the pair and check contrast |
Tailwind v4 differences
Tailwind v4 moves configuration into CSS. Current shadcn/ui projects created against v4 define variables with oklch() values, which are written in full such as oklch(0.205 0 0), and expose them with an @theme inline block. The dark variant is declared in CSS with @custom-variant dark (&:is(.dark *)); instead of darkMode in a config file. The model stays the same. Semantic names point to variables, and a .dark class overrides them. Check your components.json and stylesheet to see which style your project uses before copying snippets.
Exercise
Your app's destructive button text looks fine in light mode but is nearly invisible in dark mode. The Button uses bg-destructive text-destructive-foreground. Where do you look first, and what do you change?
Show answer
Look at the --destructive and --destructive-foreground values in the .dark block of the global stylesheet. The dark --destructive is likely too close in lightness to the foreground, or the foreground variable is missing from .dark and inherits an unsuitable value from :root. Adjust the two variables in .dark until the pair reaches at least 4.5:1 contrast. Do not edit the Button component.
Exercise
A teammate sets --primary: hsl(221, 83%, 53%); in :root, and bg-primary renders with no color. The Tailwind config contains primary: "hsl(var(--primary))". What went wrong, and what is the fix?
Show answer
The config wraps the variable in hsl(), so the result becomes hsl(hsl(221, 83%, 53%)), which is invalid CSS. The variable must hold only the channels. Change it to --primary: 221 83% 53%;.