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
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 ismedia
, which is determined by the system. We have to change toclass
to letdark
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 modedark
: 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>
is100vh
, which is full screenbg-white dark:bg-gray-800
: set light mode background to white, dark mode to dark graytext-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 toggleisDark
variable totrue
orfalse
Conclusion
dark
has to be placed earlier in the HTML tree. That’s why we have to usedark
utility on the<body>
anddark
variant on the child element