Implementing dark mode with TailwindCSS is not that new. Experimental support was added in September 2020 and being promoted to a first class citizen in November 2020 when TailwindCSS was updated to v2.
I'm currently using version 3 of TailwindCSS with the amazing Typography plugin. Dark mode is already activated because I am using the JIT (just-in-time) mode and is leveraging prefers-color-scheme
to automatically switch between light and dark mode.
Since my site is very simple the changes were just a few lines of code. Just use the dark
modifier in front of all classes that should be applied when the user prefers dark mode. In my case, most work was done with these few lines of code:
<body class="bg-gray-50">- <body class="bg-gray-50 dark:bg-gray-800 dark:text-gray-100">+ </body> </body>
a {- @apply hover:text-gray-700 + @apply hover:text-gray-700 dark:hover:text-gray-400 // ; }
After updating the Typography plugin to the latest version using npm install -D @tailwindcss/typography@latest
the only change needed to use the default inverted dark mode is to add one class:
<div class="prose">- + <div class="prose dark:prose-invert"><!-- [tl! ++] --></div> </div>
Now, to get all the details right, go through your site to spot everything that is not properly styled when using dark mode.
Tip: Using Chrome with the dev tools open, hit
Cmd + Shift + P
to open the command palette. Typeprefers-color-scheme
and choose the simulate option fordark
orlight
to quickly review your changes without needing to change your system preferences.
This may be the trickiest part if your site is larger. In my case I needed to change 6 files or 8 lines to make it everything look good.
I hope this post helped you! If you have any questions, hit me up on X 😊.
You might find these related articles helpful or interesting, make sure to check them out!