How to use dark mode with Tailwind CSS

One of the features that Tailwind CSS provides is the ability to easily create dark mode styles for your web pages. In this article, we'll take a look at how to use Tailwind CSS's dark mode feature.

The first step in using Tailwind CSS's dark mode feature is to enable it in your project. This can be done by including the @tailwindcss/typography and @tailwindcss/aspect-ratio modules in your project, and adding the dark config to your Tailwind CSS config file.

Example:

module.exports = {
  theme: {
    extend: {},
    config: {
      dark: 'class',
    },
  },
  variants: {},
  plugins: [
    require('@tailwindcss/typography'),
    require('@tailwindcss/aspect-ratio'),
  ],
}

Once you have enabled the dark mode feature, you can use the dark: prefix in your classes to create dark mode styles. For example, you can use the dark:text-white class to set the text color to white in dark mode.

Once you have enabled the dark mode feature, you can use the dark: prefix in your classes to create dark mode styles. For example, you can use the dark:text-white class to set the text color to white in dark mode.

<div class="dark:bg-gray-800 dark:text-white">
  This text will be white in dark mode
</div>

You can also use the dark:group-hover: and dark:focus: prefix to create styles that only apply in dark mode when the group or element is hovered or in focus.

You can also use the dark:not- prefix to negate the styles you've written with the dark: prefix

<div class="bg-white dark:not-bg-white">
  This text will be white in light mode, and will not have a background color in dark mode
</div>

Tailwind CSS also provides a dark-mode-switch utility class that you can use to create a button to toggle between light and dark mode.

<button type="button" class="dark-mode-switch" aria-label="Toggle dark mode"></button>

You can also use JavaScript to toggle the dark class on the html tag and change your site's theme.

Example:

document.querySelector('.dark-mode-switch').addEventListener('click', () => {
  document.querySelector('html').classList.toggle('dark');
});

In summary, Tailwind CSS's dark mode feature makes it easy to create dark mode styles for your web pages. By including the @tailwindcss/typography and @tailwindcss/aspect-ratio modules in your project and adding the dark config to your Tailwind CSS config file, you can use the dark: prefix in your classes to create dark mode styles and use the dark-mode-switch class to create a toggle button.

Continue Reading