CPCODELAB
Tailwind CSS

Dark Mode

10 min read

Adding Dark Mode Support

Tailwind's dark: variant applies utilities only when dark mode is active. In v4, dark mode is configured via a CSS variant declaration in your stylesheet.

Media-Query Dark Mode (default)

css
@import "tailwindcss";

/* dark: responds to the OS preference automatically */
/* No extra configuration needed in v4 */

Class-Based Dark Mode

css
@import "tailwindcss";

@variant dark (&:where(.dark, .dark *));

With class-based dark mode, add or remove the dark class on <html> via JavaScript to toggle the theme. This is the approach used on sites like CPCODELAB where users can switch themes manually.

html
<body class="bg-white text-slate-900 dark:bg-slate-950 dark:text-slate-100">
  <div class="rounded-xl bg-slate-100 p-6 dark:bg-slate-800">
    <p class="text-slate-600 dark:text-slate-400">Card content</p>
  </div>
</body>

Define semantic color tokens in @theme like --color-surface and use them throughout. Then only update the token value for dark mode rather than sprinkling dark: on every element.

Ready to test yourself?
Practice Tailwind CSS— quiz & coding exercises