|

Dark times for the frontend - Dark Mode with Tailwind CSS!

As a frontend developer, you can't avoid two buzzwords at the moment - Tailwind and Dark Mode.

Tailwind already comes with dark mode support. The prefix dark: is provided for this. This is used analogously to other variants.

Implementation via dark: prefix

Example from Tailwind Docs:

<div class="bg-white dark:bg-grey-800">
  <h1 class="text-gray-900 dark:text-white">Dark mode is here!</h1>
  <p class="text-gray-600 dark:text-grey-300">
    Lorem ipsum...
  </p>
</div>

The dark prefix allows very granular control over which styles should apply in dark mode. There are no restrictions on which styles can be changed. So not only the color can be changed, but also the text size etc..

However, this approach also has a downside. Everything must always be written twice.

Implementation as Tailwind Theme

Alternatively, the dark mode can also be considered as a theme. All colors are then defined as CSS Custom Property and in the Dark Mode these are simply overwritten.

``css
/* css File: */
:root {
--color-bg-primary: rgb(200, 133, 255);
--color-text-primary: rgb(50, 50, 50);
}

.dark {
--color-bg-primary: rgb(112, 38, 173);
--color-text-primary: rgb(200, 200, 200);
}



``js
/* tailwind.config.js: */
...
  darkMode: ``class,
  theme: {
    extend: {
      textColor: {
        primary: "var(--color-text-primary)"
      },
      backgroundColor: {
        primary: "var(--color-bg-primary)"
      }
    }
  }
...

With this approach, themes can be created quite easily without having to use additional variants.

The Code Sandbox demonstrates a working example. It also shows how CSS Custom Properties can be used together with Tailwind's Opacity system.