How to Use Tailwind CSS with Svelte: Setup and Example
To use
Tailwind CSS with Svelte, install Tailwind and its dependencies, then configure postcss.config.cjs and tailwind.config.cjs. Import Tailwind’s styles in your main src/app.css and include that CSS in your Svelte app entry point.Syntax
Using Tailwind CSS in Svelte involves importing Tailwind’s utility classes into your component styles. You write class names directly in your Svelte component's HTML elements.
Example parts:
class="bg-blue-500 text-white p-4 rounded": applies background color, text color, padding, and rounded corners.- Tailwind classes are utility-first, so you combine small classes to style elements.
svelte
<script> // No special script needed for Tailwind usage </script> <button class="bg-blue-500 text-white p-4 rounded hover:bg-blue-700"> Click me </button>
Output
A blue button with white text, padding, rounded corners, and a darker blue hover effect.
Example
This example shows a minimal Svelte component styled with Tailwind CSS classes after proper setup.
svelte
<script> let count = 0; </script> <main class="flex flex-col items-center justify-center min-h-screen bg-gray-100"> <h1 class="text-3xl font-bold mb-4 text-gray-800">Counter</h1> <button class="bg-green-500 text-white px-6 py-3 rounded shadow hover:bg-green-700" on:click={() => count++} > Clicked {count} {count === 1 ? 'time' : 'times'} </button> </main>
Output
A centered page with a heading and a green button that increments a counter on each click.
Common Pitfalls
Common mistakes when using Tailwind with Svelte include:
- Not importing the Tailwind CSS file in your main entry point, so styles don’t apply.
- Missing PostCSS or Tailwind configuration files, causing build errors.
- Using outdated Tailwind versions or legacy config formats.
- Forgetting to restart the dev server after config changes.
svelte
<!-- Wrong: No Tailwind import --> <script> let count = 0; </script> <button class="bg-blue-500 text-white p-4 rounded">Click me</button> <!-- Right: Import Tailwind CSS in main.js or main.ts --> // main.js import './app.css';
Quick Reference
Steps to set up Tailwind CSS in a Svelte project:
- Install Tailwind and dependencies:
npm install -D tailwindcss postcss autoprefixer - Initialize Tailwind config:
npx tailwindcss init tailwind.config.cjs -p - Configure
tailwind.config.cjswith your Svelte files path. - Create
src/app.csswith Tailwind directives. - Import
app.cssin your main entry file. - Use Tailwind classes in your Svelte components.
Key Takeaways
Install Tailwind and PostCSS, then configure Tailwind for your Svelte files.
Import Tailwind CSS in your main entry file to apply styles globally.
Use Tailwind utility classes directly in Svelte component markup.
Restart your dev server after changing Tailwind or PostCSS configs.
Avoid missing config files or imports to prevent styling issues.