Tailwind CSS Tutorial · Interactivity and States · Lesson 17 of 27

Dark Mode

Adding dark mode with the dark: variant, following the system setting or a toggle with a class, and choosing good dark colours.

Create a free account to save this page, take notes and track your progress. Sign in

The dark: variant

bg-white dark:bg-gray-900 uses white normally and gray-900 in dark mode. By default, dark mode follows the operating system setting (prefers-color-scheme).

Dark mode with a toggle

To let users choose, switch dark: to a class on a parent (usually <html>), in your CSS:

@import "tailwindcss";
@custom-variant dark (&:where(.dark, .dark *));

Then add or remove class="dark" on <html> with a little JavaScript, and remember the choice in localStorage. The example uses the same setup to show both themes side by side:

One card in light and darkTry it yourself
<style type="text/tailwindcss">
  @custom-variant dark (&:where(.dark, .dark *));
</style>
<div class="grid sm:grid-cols-2">
  <div class="p-6">
    <div class="rounded-xl bg-white p-5 shadow ring-1 ring-gray-200 dark:bg-gray-900 dark:ring-white/10">
      <p class="font-semibold text-gray-900 dark:text-white">Light card</p>
      <p class="mt-1 text-sm text-gray-600 dark:text-gray-400">Same classes in both columns.</p>
      <button class="mt-3 rounded-md bg-sky-600 px-3 py-1.5 text-sm text-white dark:bg-sky-500">Action</button>
    </div>
  </div>
  <div class="dark bg-gray-950 p-6">
    <div class="rounded-xl bg-white p-5 shadow ring-1 ring-gray-200 dark:bg-gray-900 dark:ring-white/10">
      <p class="font-semibold text-gray-900 dark:text-white">Dark card</p>
      <p class="mt-1 text-sm text-gray-600 dark:text-gray-400">Same classes in both columns.</p>
      <button class="mt-3 rounded-md bg-sky-600 px-3 py-1.5 text-sm text-white dark:bg-sky-500">Action</button>
    </div>
  </div>
</div>

Tips for dark colours

  • Don't use pure black; gray-900/950 backgrounds with gray-100/300 text are easier on the eyes.
  • Use lighter shades of brand colours (sky-400 instead of sky-600) so they stay readable.
  • Lower shadow use; borders (dark:border-white/10) separate surfaces better in the dark.

Test yourself

By default, what decides whether dark: classes apply in Tailwind v4?

  1. The operating system's colour scheme (prefers-color-scheme)
  2. A dark class on <html>
  3. The time of day
  4. A cookie
Show answer

Answer: The operating system's colour scheme (prefers-color-scheme)

Class-based dark mode needs a @custom-variant; the default is the media query.

Was this page helpful?