Dark Mode with Tailwind

Before I started building this blog I knew that I wanted to support both light and dark mode. This can be done using the prefers-color-scheme media query. In this post I'll share how I implemented dark mode with Tailwind.

First you'll need to add a custom media query to your tailwind.config.js file.

module.exports = {
  theme: {
    extend: {
      screens: {
        dark: { raw: '(prefers-color-scheme: dark)' }
      }
    }
  }
};

Then you may use the breakpoint in your HTML.

<main class="bg-white dark:bg-black"></main>

You can also use the breakpoint within your CSS using the @screen directive.

.page {
  @apply bg-white;

  @screen dark {
    @apply bg-black;
  }
}

If you want to switch between light and dark mode you can toggle your system preferences or emulate preferred color scheme in the developer tools.

Update May 1, 2020

This has now been added to Tailwind's documentation. Adam is also planning to ship a more feature-complete version of this baked right in to Tailwind.