點燈坊

失くすものさえない今が強くなるチャンスよ

Toggling Light & Dark Mode

Sam Xiao's Avatar 2022-01-13

Dark mode is getting more and more popular. We can toggle light and dark mode by Alpine and TailwindCSS.

Version

Alpine 3.9
TailwindCSS 3.0

Dark Mode

dark000

Light & dark mode is toggled by the user.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <script src="https://unpkg.com/alpinejs" defer></script>
    <script src="https://cdn.tailwindcss.com"></script>
    <title>Alpine</title>
    <script>
      tailwind.config = {
        darkMode: "class",
      };
    </script>
  </head>
  <body x-data="{ isDark: false }" :class="{ dark: isDark }">
    <div
      class="min-h-screen bg-white text-gray-900 dark:bg-gray-800 dark:text-white"
    >
      <input type="checkbox" x-model="isDark" />
      <span x-text="isDark ? 'Dark' : 'Light'" />
    </div>
  </body>
</html>

Line 10

tailwind.config = {
  darkMode: 'class'
}
  • darkMode : the default value is media, which is determined by the system. We have to change to class to let dark utility toggle the light & dark mode

Line 15

<body x-data="{ isDark: false }" :class="{ dark: isDark }">
  • isDark : toggled by Checkbox to determine light or dark mode
  • dark : enable dark mode

Line 16

<div
  class="min-h-screen bg-white text-gray-900 dark:bg-gray-800 dark:text-white"
>
  • min-h-screen : make the height of <div> is 100vh, which is full screen
  • bg-white dark:bg-gray-800 : set light mode background to white, dark mode to dark gray
  • text-gray-900 dark:text-white : set light mode text color to dark gray, dark mode to white

Line 19

<input type="checkbox" x-model="isDark" />
<span x-text="isDark ? 'Dark' : 'Light'" />
  • isDark : use Checkbox to toggle isDark variable to true or false

Conclusion

  • dark has to be placed earlier in the HTML tree. That’s why we have to use dark utility on the <body> and dark variant on the child element

Reference

TailwindCSS, Dark Mode