Step 1: Run the Setup Command
Open your terminal and run the following command to create a complete Tailwind project with dark mode functionality:
mkdir dark-mode-tailwind && cd dark-mode-tailwind && npm init -y && npm install -D tailwindcss postcss autoprefixer && npx tailwindcss init && echo '@tailwind base;\n@tailwind components;\n@tailwind utilities;' > styles.css && echo '<!DOCTYPE html>\n<html lang="en" class="dark">\n<head>\n<meta charset="UTF-8" />\n<meta name="viewport" content="width=device-width, initial-scale=1.0" />\n<title>Dark Mode with Tailwind CSS</title>\n<link rel="stylesheet" href="dist/styles.css" />\n</head>\n<body class="bg-white dark:bg-gray-900 text-gray-800 dark:text-gray-200">\n<div class="min-h-screen flex flex-col items-center justify-center">\n<h1 class="text-4xl font-bold mb-4">Tailwind CSS Dark Mode</h1>\n<p class="mb-6">Toggle the button below to switch themes!</p>\n<button id="theme-toggle" class="px-4 py-2 bg-blue-500 text-white rounded shadow-md dark:bg-yellow-400 dark:text-black">Toggle Dark Mode</button>\n</div>\n<script src="script.js"></script>\n</body>\n</html>' > index.html && echo 'const themeToggleBtn = document.getElementById("theme-toggle");\nconst htmlElement = document.documentElement;\n\nif (localStorage.getItem("theme") === "dark") {\nhtmlElement.classList.add("dark");\n}\n\nthemeToggleBtn.addEventListener("click", () => {\nif (htmlElement.classList.contains("dark")) {\nhtmlElement.classList.remove("dark");\nlocalStorage.setItem("theme", "light");\n} else {\nhtmlElement.classList.add("dark");\nlocalStorage.setItem("theme", "dark");\n}\n});' > script.js && npm run build && npx tailwindcss -i ./styles.css -o ./dist/styles.css --watch
Step 2: Open the Project
After the command completes, open the folder in your code editor. Your files are ready, and you can test the project in any live server, such as:
npx live-server
What the Command Does
Creates a project folder (dark-mode-tailwind) and navigates into it.
Initializes the project with npm and installs Tailwind CSS dependencies.
Configures Tailwind CSS and creates the required styles.css file.
Adds a basic index.html with a dark mode toggle button.
Writes a script.js file to handle dark mode logic using localStorage.
Builds the Tailwind CSS file for immediate use.
Test the Dark Mode
Open index.html in a browser.
Click the "Toggle Dark Mode" button to switch themes.
Your preference will persist even after refreshing, thanks to localStorage!
Enjoy coding! 😊
Top comments (0)