Dark Mode

Style a dark version of your UI with the dark: prefix.

Syntaxclass="bg-white dark:bg-slate-800"

The dark: prefix applies a utility only when dark mode is active. You typically pair a light color with a dark: variant.

For example, bg-white dark:bg-slate-800 gives a white card in light mode and a dark card in dark mode.

In the demo the page is forced into dark mode so you can see the effect.

Example

Try it yourself
Loading editor…
Press Run to see the result.

When to use it

  • A SaaS dashboard respects the user's OS preference by applying dark: variants to background and text classes automatically.
  • A blog switches its card backgrounds from white to gray-800 in dark mode by adding dark:bg-gray-800 to existing white elements.
  • A developer lets users toggle dark mode manually by toggling the 'dark' class on the html element and relying on dark: utilities throughout.

More examples

OS-preference dark background

dark: variants flip the background to near-black and the text to near-white when the user's system is in dark mode.

Example Β· html
<body class="bg-white text-gray-900 dark:bg-gray-900 dark:text-gray-100">
  <p>Content adapts to OS color scheme.</p>
</body>

Dark-mode card

Every color utility has a dark: counterpart that swaps light-mode grays and whites to their dark equivalents without any JavaScript.

Example Β· html
<div class="bg-white border border-gray-200 p-6 rounded
            dark:bg-gray-800 dark:border-gray-700">
  <h2 class="text-gray-900 dark:text-white font-semibold">Article Title</h2>
  <p class="text-gray-600 dark:text-gray-400 mt-2">Summary text here.</p>
</div>

Manual dark mode toggle

With darkMode: 'class', adding the dark class to <html> activates all dark: variants site-wide, enabling user-toggled dark mode.

Example Β· html
<!-- tailwind.config.js: darkMode: 'class' -->
<html class="dark">
  <body class="bg-white dark:bg-slate-900">
    <p class="text-black dark:text-slate-100">Hello</p>
  </body>
</html>

Discussion

  • Be the first to comment on this lesson.
Dark Mode β€” Tailwind CSS | SoundsCode