Home >Web Front-end >CSS Tutorial >Dark Mode and Night Mode with Tailwind CSS and CSS Variables
Dark mode and night mode are must-haves for modern websites. They improve accessibility and give users the flexibility to choose their preferred look. Let’s dive into how you can build this feature using Tailwind CSS and CSS variables.
Start by defining the colors for your themes. These CSS variables will be inside a parent class to make switching themes easy.
/* Light Theme (Default) */ :root { --bg-color: #ffffff; --text-color: #000000; } /* Dark Theme */ .theme-dark { --bg-color: #000000; --text-color: #ffffff; } /* Solarized Theme */ .theme-solarized { --bg-color: #002b36; --text-color: #839496; }
Tailwind makes it easy to use CSS variables for styling.
<div> <h2> Adding JavaScript for Dynamic Theme Switching </h2> <p>Here’s the JavaScript to handle theme changes dynamically:<br> </p> <pre class="brush:php;toolbar:false">const themeSelect = document.getElementById("theme-select"); const rootElement = document.documentElement; // Listen for dropdown changes themeSelect.addEventListener("change", (event) => { const selectedTheme = event.target.value; // Remove all theme classes rootElement.classList.remove("theme-light", "theme-dark", "theme-solarized"); // Add the selected theme class rootElement.classList.add(selectedTheme); }); // Set default theme on load window.addEventListener("DOMContentLoaded", () => { rootElement.classList.add("theme-light"); });
Real-Time Theme Switching in Action
When users pick a theme from the dropdown, the background and text colors change instantly. This dynamic update makes the experience seamless and interactive.
Why This Approach is Awesome
Take it up a notch by saving the selected theme so it persists across sessions.
// Save the theme themeSelect.addEventListener("change", (event) => { const selectedTheme = event.target.value; rootElement.classList.remove("theme-light", "theme-dark", "theme-solarized"); rootElement.classList.add(selectedTheme); localStorage.setItem("theme", selectedTheme); }); // Load the saved theme window.addEventListener("DOMContentLoaded", () => { const savedTheme = localStorage.getItem("theme") || "theme-light"; rootElement.classList.add(savedTheme); });
Extra Tips for Dark Mode and Night Mode
With Tailwind CSS and CSS variables, creating a dynamic dark mode or night mode is straightforward and efficient. Try it out and see how it transforms your website’s user experience!
The above is the detailed content of Dark Mode and Night Mode with Tailwind CSS and CSS Variables. For more information, please follow other related articles on the PHP Chinese website!