agyanadda@gmail.com

Tailwind Dark Mode

Styling and Effects 1 min read Updated Dec 1, 2026 Topic 18 of 27

Prefix any class with dark: to apply it in dark mode.

<div class="bg-white text-slate-900 dark:bg-slate-900 dark:text-white">

Default: follow the system

By default, dark: follows the user's operating-system setting (prefers-color-scheme).

Manual toggle (class based)

To let users switch with a button, tell Tailwind v4 to use a .dark class:

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

Then add or remove dark on <html> with JavaScript, and save the choice in localStorage.

Tips

  • Do not use pure black; bg-slate-900 or bg-gray-950 is softer
  • Reduce bright colours: dark:text-slate-300
  • Check borders and shadows: dark:border-slate-700
  • Test both modes before publishing

Example

Example — Dark mode toggle HTML
<script src="https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4"></script>
<style type="text/tailwindcss">
  @custom-variant dark (&:where(.dark, .dark *));
</style>

<div id="app" class="min-h-screen p-8 bg-slate-50 text-slate-800 dark:bg-slate-900 dark:text-slate-100 transition-colors">
  <div class="flex justify-between items-center">
    <h1 class="text-2xl font-bold">Dark mode demo</h1>
    <button id="toggle" class="px-4 py-2 rounded-lg bg-slate-800 text-white dark:bg-amber-400 dark:text-slate-900">Toggle theme</button>
  </div>
  <div class="mt-6 max-w-sm rounded-xl border border-slate-200 bg-white p-5 shadow-sm dark:border-slate-700 dark:bg-slate-800">
    <h2 class="font-semibold">Course card</h2>
    <p class="text-slate-500 dark:text-slate-400">This card changes colours in dark mode.</p>
  </div>
</div>

<script>
  const root = document.documentElement;
  try { if (localStorage.getItem('theme') === 'dark') root.classList.add('dark'); } catch (e) {}
  document.getElementById('toggle').onclick = () => {
    root.classList.toggle('dark');
    try { localStorage.setItem('theme', root.classList.contains('dark') ? 'dark' : 'light'); } catch (e) {}
  };
</script>

Test Yourself With Exercises

Exercise 1 Multiple Choice

Which prefix applies a class only in dark mode?

Exercise 2 True / False

By default, Tailwind's dark mode follows the operating-system setting.

Exercise 3 Fill in the Blank

Save the user's theme choice in ___ so it stays after reload.

Frequently Asked Questions

Add the dark class with a tiny inline script in the <head>, before the page renders, instead of at the end of the body.