DEV Community

Cover image for Adding Tailwind CSS Utilities to Svelte Applications
Shawn Condon
Shawn Condon

Posted on • Edited on

Adding Tailwind CSS Utilities to Svelte Applications

If you are using SvelteKit, the Tailwind Docs make it easy to set up Tailwind in your app.

This post will walk through adding Tailwind to a regular Svelte app, one without the framework features and server-side rendering of SvelteKit.


Spin up a new Svelte application and pass the --template svelte flag, with my-svelte-app being a generic placeholder used in this example for the name of your application:

npm create vite@latest my-svelte-app --template svelte
Enter fullscreen mode Exit fullscreen mode

Once the project is fully scaffolded, run:

cd my-svelte-app
npm install
npm run dev
Enter fullscreen mode Exit fullscreen mode

cd places you in your project directory, npm install installs all the dependencies and packages listed in your project's package.json file, and npm run dev starts up the Vite development server, which compiles and serves your app so you can view and test changes as you develop.

Next, install Tailwind:

npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p
Enter fullscreen mode Exit fullscreen mode

Update your vite.config.js file:

// vite.config.js

import { defineConfig } from 'vite';
import { svelte } from '@sveltejs/vite-plugin-svelte';

export default defineConfig({
  plugins: [
    svelte()
  ] 
});
Enter fullscreen mode Exit fullscreen mode

Update your tailwind.config.js file:

// tailwind.config.js

/** @type {import('tailwindcss').Config} */
export default {
  content: ['./index.html', './src/**/*.{svelte,js,ts}'],
  theme: {
    extend: {},
  },
  plugins: [],
}
Enter fullscreen mode Exit fullscreen mode

Create a styles.css file in your src folder and drop in these Tailwind directives:

@tailwind base;
@tailwind components;
@tailwind utilities;
Enter fullscreen mode Exit fullscreen mode

Import './styles.css' in your App.svelte component:

// App.svelte

<script>
  import './styles.css'
</script>
Enter fullscreen mode Exit fullscreen mode

Add Tailwind styling:

<script>
  import './styles.css'
</script>

<main>
  <div>
    <h1 class="border-4 border-white rounded-full p-4 text-4xl text-teal-400">Hello, Tailwind</h1>
  </div>
</main>
Enter fullscreen mode Exit fullscreen mode

If not already doing so, run npm run dev to start your server and navigate to http://localhost:5173/ to see the Tailwind utilities applied:

Image description


Thank you for reading! If you enjoyed this article, please consider sharing it with your network.

Unrelated reading recommendation: Siddhartha by Herman Hesse

Top comments (0)