DEV Community

Fedor Pasynkov
Fedor Pasynkov

Posted on • Edited on

Setting Up Tailwind CSS v4 in SvelteKit: The Vite Plugin Way (A Guide Based on Real Issues)

Published: 2025-05-11

This guide shows you how to easily set up and integrate the latest Tailwind CSS v4 with your SvelteKit project. We'll walk you through the process step-by-step, focusing on the official and recommended @tailwindcss/vite plugin, which simplifies the setup and avoids complex PostCSS configurations.

Tailwind CSS v4 is currently in Alpha/RC (Release Candidate) stage (as of 2025-05-11 - please update this date). While this means you get to work with cutting-edge features, it also means some aspects might change before the stable release. This guide reflects the current state and best practices. Always refer to the official Tailwind CSS documentation and the Tailwind CSS v4 release notes/discussions for the most up-to-date information.

We'll cover everything from initial project setup with SvelteKit's CLI to configuring Tailwind v4 and using it within your Svelte components.

Important Compatibility Note: Tailwind CSS v4 is designed for modern browsers: Safari 16.4+, Chrome 111+, Firefox 128+. If you need to support older browsers, please stick with v3.4 as v4 relies on modern CSS features like @property and color-mix().

Prerequisites

Before you begin, ensure you have the following:

  • Node.js and npm/yarn/pnpm: Installed on your system. You can download Node.js from nodejs.org.
  • A SvelteKit Project: You can create a new one using npm create svelte@latest my-app or npx sv create . as shown below. If you have an existing SvelteKit project, you can adapt the steps.
  • Package Manager: Know which package manager you're using (npm, yarn, or pnpm).

1. Creating Your SvelteKit Project with Tailwind CSS Integration (via npx sv create .)

This section details how to add Tailwind CSS v4 to SvelteKit during project initialization. The npx sv create . CLI provides a streamlined way to scaffold a SvelteKit project and include Tailwind CSS during the initial setup.

  1. Create your project directory: Open your terminal, create the directory for your frontend application, and navigate into it:

    mkdir frontend
    cd frontend
    
  2. Initialize the SvelteKit project using sv: Run the following command in the directory to start your SvelteKit Tailwind v4 integration:

    npx sv create .
    
  3. Follow the interactive prompts:

    • Select your SvelteKit template.
    • Answer questions about TypeScript, ESLint, Prettier, and your adapter.
    • Crucially, when asked "What would you like to add to your project?", use your arrow keys and spacebar to select the tailwind option.
    • Choose your package manager (e.g., npm, yarn, or pnpm).
    • The CLI will install dependencies, including Tailwind CSS, and likely create some initial configuration files.

2. Verifying Installed Packages for a Smooth Tailwind v4 Setup in SvelteKit

After npx sv create . completes, let's ensure you have the correct packages installed for integrating Tailwind via the Vite plugin. This is key for a successful Tailwind v4 setup in SvelteKit.

  1. Open package.json: Navigate to the root of your frontend directory (./frontend/) and open the package.json file.
  2. Check devDependencies: Confirm that the following packages are present (in v4-compatible versions, often @latest or @next for pre-releases):

    • tailwindcss (v4.x) - The core Tailwind CSS library.
    • @tailwindcss/vite - The official Vite plugin for Tailwind CSS. (Crucial for this guide!) You can find more about it on npmjs.com.
    • postcss (May be installed as a dependency of Vite or SvelteKit; might be needed for other PostCSS plugins, but not for Tailwind integration via the Vite plugin itself)
    • autoprefixer (Not required for vendor prefixes in v4 when using the Vite plugin, but might be present if added by the CLI or for other purposes)
    • @sveltejs/kit and @sveltejs/vite-plugin-svelte (installed by the CLI, essential for SvelteKit projects. See SvelteKit docs).
  3. Install or Uninstall as Needed:

    # If @tailwindcss/vite is missing:
    npm install -D @tailwindcss/vite
    
    # If @tailwindcss/postcss was installed instead of @tailwindcss/vite:
    # npm uninstall -D @tailwindcss/postcss # Uninstall if you don't need the PostCSS plugin
    npm install -D @tailwindcss/vite
    
    # autoprefixer and postcss-import are NOT needed for Tailwind v4 integration via the Vite plugin.
    # You can uninstall them if they aren't required for other purposes:
    # npm uninstall -D autoprefixer postcss-import
    

3. Step-by-Step: Configuring SvelteKit's Vite Setup for Tailwind CSS v4

Since you're integrating Tailwind via the @tailwindcss/vite plugin and skipping the PostCSS config file approach, you'll configure Tailwind directly in your Vite configuration. This is a central part of the Tailwind v4 configuration in SvelteKit.

  1. Open vite.config.ts (or .js): This file is located in the root of your frontend directory.
  2. Configure Vite Plugins: Ensure the tailwindcss() plugin, imported from @tailwindcss/vite, is added to the root plugins array of your Vite configuration:

    import { defineConfig } from 'vite';
    import { sveltekit } from '@sveltejs/kit/vite';
    import tailwindcss from '@tailwindcss/vite'; // Import the Vite plugin
    
    export default defineConfig({
      plugins: [
        sveltekit(),
        tailwindcss(), // Add the Tailwind CSS Vite plugin here!
      ],
      css: {
        // Make sure there is no 'postcss' section configured for Tailwind integration here.
        // If a 'postcss' section exists (e.g., added by the CLI or for other plugins like Autoprefixer),
        // ensure it does NOT include the Tailwind CSS plugin.
        // postcss: { plugins: [] },
    
        // A community recommendation (might help with Vite plugin issues):
        // transformer: 'lightningcss'
      },
    });
    
  3. Optional: Configure CSS Transformer: Some users report that setting css.transformer: 'lightningcss' in vite.config.ts can help resolve certain issues when using the @tailwindcss/vite plugin. Add this line to the css section if you encounter unexpected behavior:

      css: {
        transformer: 'lightningcss'
      },
    

4. Importing Tailwind CSS v4 in Your Main SvelteKit CSS File

Locate the main CSS file that is imported somewhere in your SvelteKit application (e.g., src/app.css). This step is essential to add Tailwind CSS v4 to SvelteKit's styling pipeline.

  1. Use ONLY @import "tailwindcss";: According to the official Tailwind CSS v4 documentation, the correct and only recommended way to include Tailwind's base styles, components, and utilities is with a single @import directive. The @tailwind base;, @tailwind components;, and @tailwind utilities; directives have been removed in v4.

    @import "tailwindcss";
    

    Remove any other old @import or @tailwind directives from this file.

5. Mastering Tailwind CSS v4 Theme Configuration in SvelteKit

In Tailwind CSS v4, the primary and recommended approach for theme configuration shifts to using CSS directly. Understanding this is key for your SvelteKit Tailwind v4 integration.

  • Configuration via @theme in CSS (Recommended v4 Approach)

    • Use @theme in your main CSS file: Define your custom theme properties directly in your main CSS file (e.g., src/app.css) using the @theme directive. These properties will become CSS variables and Tailwind theme tokens. With this approach, the tailwind.config.js file is not needed for theme customization, only potentially for content paths.

      @import "tailwindcss";
      
      @theme {
        /* Define your custom theme properties as CSS variables */
        --color-brand-primary: #3490dc;
        --font-family-heading: "Georgia", serif;
        --spacing-128: 32rem;
        /* ... other theme variables */
      }
      
      /* Rest of your styles */
      
    • Automatic Content Detection and @source: Tailwind v4 automatically scans most project files. If you need to include files from non-standard locations (e.g., component libraries in node_modules), use the @source directive in the same CSS file:

      @import "tailwindcss";
      @source "../node_modules/@my-company/ui-lib";
      @theme { /* ... */ }
      
    • Using tailwind.config.js for Content (Optional): The tailwind.config.js file can still be used solely for defining the content section if you prefer explicitly listing paths or if auto-detection is insufficient:

      /** @type {import('tailwindcss').Config} */
      export default {
        content: [
          './src/**/*.{html,js,svelte,ts}',
          // Explicitly list paths here
        ],
        theme: {
          extend: {
            // This section can be empty or removed if using @theme in CSS
          },
        },
        plugins: [], // corePlugins, safelist, separator options are NOT supported in v4 JS config
      };
      

      If you use tailwind.config.js for content, you generally don't need the @config directive in your CSS when using the Vite plugin and @theme for theme definition.

6. Effectively Using Tailwind CSS v4 in Svelte Components (<style> blocks)

In Tailwind CSS v4, styles defined within Svelte component <style> blocks (or CSS Modules) do not automatically have access to theme variables, custom utilities, and variants defined in your main CSS file (app.css). Here's how to handle it when you integrate Tailwind 4 with SvelteKit components:

  • Use @reference (for access to @apply, @utility, and @theme definitions): To gain access to definitions made using @apply, @utility, or @theme in your main CSS file, use the @reference directive within the component's <style> block, pointing to your main CSS file:

    <style>
      @reference "../app.css"; /* Path to your main CSS file */
    
      h1 {
        @apply text-2xl font-bold text-blue-600; /* @apply should now work */
      }
      /* You can also use CSS variables here */
      /* color: var(--color-blue-600); */
    </style>
    
    <h1>Hello world!</h1>
    
  • Use CSS Variables Directly (Preferred): Often, instead of @apply, you can directly use the corresponding Tailwind CSS variables in your <style> blocks. This is the preferred approach as it's more performant and doesn't require @reference for theme variables defined via @theme in the main CSS:

    <style>
      /* No @reference needed if only using theme variables */
      h1 {
        color: var(--color-blue-600); /* Access a color variable */
        font-size: var(--text-2xl); /* Access a text size variable */
        /* ... other styles using variables */
      }
    </style>
    
    <h1>Hello world!</h1>
    

7. Key General v4 Changes and Recommendations for SvelteKit Developers

Be aware of these general changes in Tailwind v4 that might affect your SvelteKit Tailwind v4 integration:

  • Removed/Renamed Utilities: Many deprecated utilities are removed, some are renamed (e.g., outline-none to outline-hidden), scales are changed (shadow, blur, rounded), and default values are updated (ring from 3px to 1px, border/ring colors to currentColor). Always refer to the official Tailwind CSS v4 upgrade guide for a complete list.
  • space-x/space-y Selector Change: The selector used by these utilities has changed, which might require adjustments in some complex layouts. Consider using flex or grid with gap as an alternative.
  • Custom Utilities (@utility): Use the @utility directive instead of @layer utilities and @layer components.

    @utility my-custom-utility {
      /* Your styles */
    }
    
  • Variables in Arbitrary Values: The syntax for using CSS variables in arbitrary values changed from square brackets to parentheses: bg-[--var] -> bg-(--var).

  • Prefixes: If you use a prefix, the syntax is now prefix:class (e.g., tw:flex). Configure it within the @import rule: @import "tailwindcss" prefix(tw);.

  • Using theme(): Using CSS variables directly (var(--color-...)) is recommended. If you use theme(), the syntax is now theme(--variable-name) (e.g., theme(--breakpoint-xl)).

  • Theme in JavaScript: The resolveConfig function is removed. Use getComputedStyle to access theme CSS variables in JS.

Always consult the official Tailwind CSS documentation for the most current troubleshooting advice.

Conclusion and Next Steps

By following this guide, focusing on the @tailwindcss/vite plugin integration, you should be able to successfully set up and integrate Tailwind CSS v4 with your SvelteKit project. This approach aligns with the latest v4 practices, helping you avoid potential issues related to older PostCSS configurations.

Remember that Tailwind CSS v4 is an evolving tool. Keep an eye on the official Tailwind CSS blog and documentation for updates and new features.


I'd love to hear from you!

  • Did you find this guide helpful for your SvelteKit Tailwind v4 setup?
  • Are there any other aspects of Tailwind v4 or SvelteKit integration you'd like to see covered?
  • Encountered any specific issues or found other solutions?

Please leave a comment below to share your experience, ask questions, or suggest improvements! Your feedback helps make this guide better for everyone.

Happy coding!

Top comments (1)