For this project we will be using npm for package management. You can follow this steps to create a minimal Astro 5 with Tailwind CSS 4 project and implement a basic theme toggle button.
Prerequisites:
- NodeJs installed
- Code editor download here
1. Create a new Astro project
# Create a new project with npm
npm create astro@latest my-astro-project
If you don't have installed create astro just accept the installation. During the initial setup, select the options you prefer (generally "Empty" is a good option to start with).
Navigate to the project directory
cd my-astro-project
2. Install Tailwind CSS 4
Install Tailwind CSS based on the integration with astro in tailwindcss docs you can check here:
npm install tailwindcss @tailwindcss/vite
3. Configure Tailwind CSS for Astro
Modify the atro.config.mjs file:
import { defineConfig } from "astro/config";
// add this line
import tailwindcss from "@tailwindcss/vite";
export default defineConfig({
// add this code
vite: {
plugins: [tailwindcss()],
},
// add this code
});
4. Create the global CSS file
Create a file at src/styles/global.css with the following content:
@tailwindcss;
/* Create a custom Tailwind variant for dark mode.
* It applies styles when .dark is present on the element.
* :where(.dark, .dark *) ensures low specificity for better overrides.
*/
@custom-variant dark (&:where(.dark, .dark *));
5. Add content to index
Modify the src/pages/index.astro file with this content:
---
---
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>My Astro Theme Toggle</title>
</head>
<body class="transition-colors duration-300 bg-white text-black dark:bg-gray-900 dark:text-white">
<div class="container mx-auto p-4 flex items-center justify-center">
<h1 class="text-2xl font-bold mb-4">Astro Site + Tailwind</h1>
<button
id="theme-toggle"
class="px-4 py-2 bg-gray-200 dark:bg-gray-700 rounded-md"
>
Toggle Theme
</button>
<div class="mt-8">
<p>More content...</p>
</div>
</div>
<script>
// Simple script to toggle the theme
document.getElementById('theme-toggle')?.addEventListener('click', () => {
document.body.classList.toggle('dark');
});
</script>
</body>
</html>
6. Run the development server
npm run dev
This will start the Astro development server. Navigate to http://localhost:4321 in your browser to see your site and test the theme toggle button.
Top comments (0)