UIGetting startedReact
Dark mode
Each token has a light and a dark value. One class on the root element picks the dark ones, for every component at once.
Light and dark
The theme writes every token twice. The values on :root are the light mode and always apply. The values on .dark are the dark mode: once <html class="dark"> is set, they win: .dark weighs the same as :root and comes after it. Nothing in a component changes: a Dialog paints bg-popover in both modes, and --popover is what moves.
A token without a dark value keeps its light one. The table on Theming shows both columns.
The dark: variant
Tailwind CSS's own dark: variant follows the operating system's setting. The theme redefines it to follow the same class as the tokens, so the reader's choice decides both. This line comes from packages/ui/tokens/base.css:
@custom-variant dark (&:is(.dark *));&:is(.dark *) matches any element inside the dark root, so dark:shadow-none in your own markup turns on with the tokens.
Before the first paint
Set the class before the page draws, or a reader who chose dark sees one light frame. A small script at the top of <head> in index.html runs before anything else: it uses the stored choice, else the system's.
<script>
try {
const stored = localStorage.getItem('theme')
const dark = stored ? stored === 'dark' : matchMedia('(prefers-color-scheme: dark)').matches
document.documentElement.classList.toggle('dark', dark)
} catch {}
</script>A toggle
A button that flips the class and stores the choice under the same key the script reads, written with the registry's Button for React:
import { useState } from 'react'
import { Button } from '@/components/ui/button'
export function ThemeToggle() {
const [dark, setDark] = useState(() => document.documentElement.classList.contains('dark'))
function toggle() {
const next = !dark
document.documentElement.classList.toggle('dark', next)
localStorage.setItem('theme', next ? 'dark' : 'light')
setDark(next)
}
return (
<Button variant="outline" aria-pressed={dark} onClick={toggle}>
Dark mode
</Button>
)
}
Following the system
The script reads the system's setting once. To follow it while the page is open, listen for its change, and leave the class alone once the reader picked a mode:
const query = matchMedia('(prefers-color-scheme: dark)')
query.addEventListener('change', (event) => {
// Only while the reader has not picked a mode themselves.
if (!localStorage.getItem('theme')) {
document.documentElement.classList.toggle('dark', event.matches)
}
})The previews on this site follow its own theme toggle.