DEV Community

Cover image for [06 | CSS 05] A Comprehensive Guide to Setting Up and Using Tailwind CSS with Vite
Anik Paul
Anik Paul

Posted on

[06 | CSS 05] A Comprehensive Guide to Setting Up and Using Tailwind CSS with Vite

Tailwind CSS is a utility-first CSS framework that empowers you to build modern and maintainable user interfaces directly in your markup. With thousands of composable utility classes, you can design with precision while writing minimal custom CSS.

Pairing it with Vite, a blazing-fast build tool that offers instant server start and lightning-fast hot module replacement, makes for a modern and efficient development experience.

This guide is your complete walkthrough - from setting up Tailwind with Vite to unlocking advanced features like @apply, dark mode, custom themes, and optimization tips for production deployment.


1. Setting Up Tailwind CSS with Vite (2025 Method)

Let's begin by initializing a new project using Vite, then install and configure Tailwind CSS.


Step 1: Create a New Vite Project

Run the following in your terminal:

npm create vite@latest my-tailwind-project
cd my-tailwind-project
npm install
Enter fullscreen mode Exit fullscreen mode

When prompted, choose a framework (you can pick React, Vue, or Vanilla JavaScript; this guide assumes React for components but the setup is the same for all).

If you're using TypeScript:

npm create vite@latest my-tailwind-project --template react-ts
Enter fullscreen mode Exit fullscreen mode

Step 2: Install Tailwind CSS and Dependencies

Tailwind needs PostCSS and Autoprefixer to work with modern CSS builds.

Install the latest versions:

npm install -D tailwindcss postcss autoprefixer
Enter fullscreen mode Exit fullscreen mode

Then initialize configuration files:

npx tailwindcss init -p
Enter fullscreen mode Exit fullscreen mode

This will create two new config files in your root directory:

tailwind.config.js
postcss.config.js
Enter fullscreen mode Exit fullscreen mode

Step 3: Set Template Paths

Edit your tailwind.config.js to specify the files where Tailwind should look for class usage. Update it like so:

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

This configuration ensures Tailwind only includes the CSS you use in your final production bundle.


Step 4: Add Tailwind Directives

Create a CSS file inside your src/ folder (commonly named index.css or main.css) and include Tailwind’s base, components, and utilities:

/* src/index.css */
@tailwind base;
@tailwind components;
@tailwind utilities;
Enter fullscreen mode Exit fullscreen mode

Make sure this file is imported in your main entry point (e.g., main.jsx or main.tsx):

// main.jsx or main.tsx
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import './index.css'; // Import Tailwind styles

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
Enter fullscreen mode Exit fullscreen mode

Step 5: Start the Development Server

Now you’re ready to go:

npm run dev
Enter fullscreen mode Exit fullscreen mode

You should now be able to use Tailwind classes in your markup and see them applied instantly.


2. Using Tailwind Utility Classes

Tailwind CSS is built around utility classes - small, single-purpose classes you add directly in your HTML (or JSX) to style elements.

Let’s look at a simple example using Tailwind in a React component:

function Hero() {
  return (
    <section className="bg-gray-100 p-8 rounded-lg shadow-md">
      <h1 className="text-3xl font-bold text-blue-600 mb-2">Welcome</h1>
      <p className="text-gray-700">This is a Tailwind-powered React project.</p>
    </section>
  );
}
Enter fullscreen mode Exit fullscreen mode

Each class like text-3xl, font-bold, and bg-gray-100 maps directly to a specific style in Tailwind's utility system.


2.1 Text and Typography Utilities

Utility Description Example
text-sm to text-9xl Controls font size text-xl = 1.25rem
font-light to font-black Controls font weight font-semibold
text-center, text-left Aligns text text-center
leading-tight Line height leading-loose
tracking-widest Letter spacing Wider character spacing
<p class="text-lg font-medium text-gray-800 tracking-wide">
  Tailwind typography is fully composable.
</p>
Enter fullscreen mode Exit fullscreen mode

2.2 Spacing and Layout

Tailwind uses a 4px scale (by default) for spacing utilities.

Utility Prefix Description Example
m-, mx-, my- Margin mt-4, mx-auto
p-, px-, py- Padding p-6, py-2
space-x-, space-y- Sibling spacing space-x-4
<div class="p-4 space-y-3">
  <p class="bg-gray-100 p-2">Item 1</p>
  <p class="bg-gray-100 p-2">Item 2</p>
</div>
Enter fullscreen mode Exit fullscreen mode

2.3 Flexbox and Grid Layout

Tailwind makes layout creation seamless using flex and grid utilities.

Flexbox Example:

<div class="flex items-center justify-between p-4 bg-white">
  <span>Logo</span>
  <nav class="flex gap-4">
    <a href="#" class="text-blue-600">Home</a>
    <a href="#" class="text-gray-600">About</a>
  </nav>
</div>
Enter fullscreen mode Exit fullscreen mode
Utility Function
flex, inline-flex Enables flexbox
items-center Aligns items vertically
justify-between Spaces children horizontally
gap-4 Adds spacing between children

Grid Example:

<div class="grid grid-cols-3 gap-4 p-4">
  <div class="bg-blue-100">1</div>
  <div class="bg-blue-200">2</div>
  <div class="bg-blue-300">3</div>
</div>
Enter fullscreen mode Exit fullscreen mode
Utility Function
grid, grid-cols-* Defines number of columns
gap-* Adds spacing between cells

2.4 Responsive Design

Tailwind is mobile-first, and all utilities can be made responsive using prefixes:

<div class="p-4 text-base sm:text-lg md:text-xl lg:text-2xl">
  Responsive text sizing
</div>
Enter fullscreen mode Exit fullscreen mode
Prefix Min Width Use Case
sm: 640px Tablets (portrait)
md: 768px Tablets (landscape)
lg: 1024px Laptops
xl: 1280px Desktops
2xl: 1536px Large desktops

2.5 Pseudo-Classes and State Variants

Tailwind supports hover, focus, active, and more using simple prefixes:

<button class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded">
  Hover Me
</button>
Enter fullscreen mode Exit fullscreen mode
Variant Prefix Applies On
hover: On mouse hover
focus: On element focus
active: On click/active
disabled: When disabled
group-hover: When parent .group is hovered

2.6 Customizing the Theme

Extend Tailwind’s default design system in your tailwind.config.js.

export default {
  content: ['./index.html', './src/**/*.{js,ts,jsx,tsx}'],
  theme: {
    extend: {
      colors: {
        primary: '#0f172a',
        secondary: '#facc15',
      },
      fontFamily: {
        display: ['"Poppins"', 'sans-serif'],
        body: ['"Open Sans"', 'sans-serif'],
      },
    },
  },
  plugins: [],
};
Enter fullscreen mode Exit fullscreen mode

This makes text-primary, bg-secondary, font-display, etc., available throughout your project.


2.7 Creating Reusable Components with @apply

You can bundle Tailwind utilities into reusable classes with @apply.

@layer components {
  .btn {
    @apply bg-yellow-500 text-white px-4 py-2 rounded hover:bg-yellow-600;
  }

  .card {
    @apply p-6 bg-white shadow-md rounded-lg;
  }
}
Enter fullscreen mode Exit fullscreen mode

Then in JSX:

<button className="btn">Buy Now</button>
<div className="card">Product details...</div>
Enter fullscreen mode Exit fullscreen mode

3. Advanced Features in Tailwind CSS

Tailwind CSS offers much more than utility classes. In this section, we’ll explore advanced features that unlock powerful workflows — including dark mode, plugin support, animation, the JIT engine, and safelisting dynamic class names.


3.1 Enabling and Using Dark Mode

Tailwind CSS includes first-class support for dark mode, allowing you to build light/dark responsive UIs easily.

Step 1: Enable Dark Mode in tailwind.config.js

There are two strategies:

Mode Behavior
media Follows system preference via prefers-color-scheme
class Uses a manual .dark class on the root element
export default {
  darkMode: 'class', // or 'media'
  content: ['./index.html', './src/**/*.{js,ts,jsx,tsx}'],
  theme: { extend: {} },
  plugins: [],
};
Enter fullscreen mode Exit fullscreen mode

Step 2: Use Dark Mode Utilities

You can now use dark: variants in your classes.

<div class="bg-white text-black dark:bg-gray-900 dark:text-white p-4">
  This box switches theme based on dark mode.
</div>
Enter fullscreen mode Exit fullscreen mode

Step 3: Toggling Dark Mode (Class-Based)

If using 'class', you need JavaScript to toggle dark mode:

// Toggle dark mode manually
document.documentElement.classList.toggle('dark');
Enter fullscreen mode Exit fullscreen mode

To enable dark mode by default based on system preference:

if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
  document.documentElement.classList.add('dark');
}
Enter fullscreen mode Exit fullscreen mode

3.2 Tailwind CSS Plugins

Tailwind offers official plugins that extend its base utilities. You can install and register them in tailwind.config.js.


1. Typography Plugin (@tailwindcss/typography)

Great for styling markdown or blog content.

npm install -D @tailwindcss/typography
Enter fullscreen mode Exit fullscreen mode
import typography from '@tailwindcss/typography';

export default {
  plugins: [typography],
};
Enter fullscreen mode Exit fullscreen mode

Usage:

<article class="prose lg:prose-xl">
  <h1>This is beautifully styled markdown</h1>
  <p>All paragraph, heading, and list styles are pre-optimized.</p>
</article>
Enter fullscreen mode Exit fullscreen mode

2. Forms Plugin (@tailwindcss/forms)

Simplifies and normalizes form styling.

npm install -D @tailwindcss/forms
Enter fullscreen mode Exit fullscreen mode
import forms from '@tailwindcss/forms';

export default {
  plugins: [forms],
};
Enter fullscreen mode Exit fullscreen mode

Usage:

<input type="text" class="form-input" placeholder="Your name" />
<select class="form-select"><option>Option 1</option></select>
Enter fullscreen mode Exit fullscreen mode

3. Aspect-Ratio Plugin (@tailwindcss/aspect-ratio)

Maintains consistent aspect ratios (useful for videos, images).

npm install -D @tailwindcss/aspect-ratio
Enter fullscreen mode Exit fullscreen mode
import aspectRatio from '@tailwindcss/aspect-ratio';

export default {
  plugins: [aspectRatio],
};
Enter fullscreen mode Exit fullscreen mode

Usage:

<div class="aspect-w-16 aspect-h-9">
  <iframe src="https://www.youtube.com/embed/example" class="w-full h-full"></iframe>
</div>
Enter fullscreen mode Exit fullscreen mode

3.3 Animations and Transitions

Tailwind includes built-in classes for animation and transition effects.

Transitions

Class Purpose
transition Enables transition
duration-300 Sets duration
ease-in-out Sets easing

Example:

<button class="bg-blue-500 hover:bg-blue-700 text-white transition duration-300 ease-in-out px-4 py-2 rounded">
  Hover Me
</button>
Enter fullscreen mode Exit fullscreen mode

Animations

Built-in animation utilities like animate-spin, animate-ping, animate-bounce:

<div class="w-12 h-12 bg-blue-500 rounded-full animate-ping"></div>
Enter fullscreen mode Exit fullscreen mode

You can also define custom keyframes:

export default {
  theme: {
    extend: {
      animation: {
        fadeIn: 'fadeIn 1s ease-out forwards',
      },
      keyframes: {
        fadeIn: {
          '0%': { opacity: 0 },
          '100%': { opacity: 1 },
        },
      },
    },
  },
};
Enter fullscreen mode Exit fullscreen mode

Usage:

<div class="animate-fadeIn">Hello</div>
Enter fullscreen mode Exit fullscreen mode

3.4 Just-In-Time (JIT) Engine

Tailwind's JIT engine is enabled by default since v3. It compiles utilities on demand - no need to worry about purging unused classes anymore.

Key benefits:

  • Lightning-fast builds
  • Arbitrary values (w-[430px], text-[#1f2937])
  • Conditional variants (hover:enabled:bg-blue-600)
  • Advanced responsive classes (lg:hover:text-red-500)

3.5 Safelisting Classes

If you're dynamically generating classes (like text-${color}), Tailwind may purge them unless you safelist them.

In tailwind.config.js:

export default {
  content: ['./index.html', './src/**/*.{js,ts,jsx,tsx}'],
  safelist: [
    'text-red-500',
    'bg-green-500',
    {
      pattern: /^text-(red|green|blue)-(100|500|700)$/,
    },
  ],
};
Enter fullscreen mode Exit fullscreen mode

4. Deployment, Optimization, and Best Practices

With the styling complete, the next step is preparing your Tailwind project for production. In this section, we’ll cover optimization techniques, deployment options, component libraries, formatting tools, and workflow improvements.


4.1 Production Optimization

Tailwind CSS automatically optimizes your build when you're in production mode.

If you're using Vite, this is already built-in.

Production Command

npm run build
Enter fullscreen mode Exit fullscreen mode

Vite detects NODE_ENV=production and automatically tree-shakes unused Tailwind classes - thanks to Tailwind's JIT engine and the content configuration in tailwind.config.js.

To inspect your final build:

npx vite preview
Enter fullscreen mode Exit fullscreen mode

4.2 Deployment Tips

Vite builds your site into a dist/ folder, which you can deploy to any static hosting provider.

Recommended Hosting Options:

Platform Supports SPA Free Tier Deployment Method
Netlify Yes Yes Connect Git or drag-and-drop
Vercel Yes Yes Git integration or CLI
GitHub Pages Yes Yes Configure for static site
Firebase Hosting Yes Yes firebase deploy

Example: Deploying to Netlify

  1. Push your project to a Git repository (GitHub, GitLab, etc.)
  2. Visit Netlify
  3. Click "New Site from Git"
  4. Choose your repo
  5. Set build command:
   npm run build
Enter fullscreen mode Exit fullscreen mode
  1. Set publish directory:
   dist
Enter fullscreen mode Exit fullscreen mode
  1. Deploy 🚀

4.3 Component Libraries and Ecosystem Integration

Tailwind works extremely well with Headless UI and ShadCN/UI, giving you full accessibility and functionality without sacrificing design freedom.


1. Headless UI

Headless UI (by Tailwind Labs) offers unstyled, accessible UI components for React and Vue.

Install:

npm install @headlessui/react
Enter fullscreen mode Exit fullscreen mode

Example: Accessible Modal

<Dialog open={isOpen} onClose={() => setIsOpen(false)}>
  <Dialog.Panel className="p-6 bg-white rounded-lg shadow-lg">
    <Dialog.Title className="text-xl font-semibold">Modal Title</Dialog.Title>
    <p>This modal uses Tailwind styles and Headless UI behavior.</p>
  </Dialog.Panel>
</Dialog>
Enter fullscreen mode Exit fullscreen mode

2. ShadCN/UI

ShadCN/UI is a popular collection of styled, accessible components built with Tailwind and Radix.

Install:

npx shadcn-ui@latest init
Enter fullscreen mode Exit fullscreen mode

Then use ready-made components like:

import { Button } from "@/components/ui/button";

<Button variant="default">Click Me</Button>
Enter fullscreen mode Exit fullscreen mode

ShadCN/UI also automatically integrates Prettier, clsx, and tailwind-variants for scalable styling.


4.4 Prettier + Linting for Tailwind Projects

Maintain consistent formatting using Prettier and ESLint, especially for class ordering.

Step 1: Install Prettier Plugin

npm install -D prettier prettier-plugin-tailwindcss
Enter fullscreen mode Exit fullscreen mode

Step 2: Add Prettier Config

Create prettier.config.cjs:

module.exports = {
  plugins: ['prettier-plugin-tailwindcss'],
  singleQuote: true,
  semi: false,
};
Enter fullscreen mode Exit fullscreen mode

This plugin sorts Tailwind classes in a logical order based on functionality (layout → spacing → typography → colors, etc.).


Bonus: Tailwind Class Sorting Example

Before Prettier plugin:

<div class="text-center p-2 bg-gray-200 rounded-lg text-sm">
Enter fullscreen mode Exit fullscreen mode

After Prettier plugin:

<div class="bg-gray-200 p-2 text-center text-sm rounded-lg">
Enter fullscreen mode Exit fullscreen mode

4.5 Best Practices and Tips

1. Use Utility-First Approach Strategically

Start with utility classes, and use @apply to abstract common patterns into custom classes only when needed.


2. Avoid Deeply Nesting JSX Classes

Break complex UIs into components. Don’t let Tailwind classes grow unreadably long in single tags.

Bad:

<div className="flex items-center justify-between bg-gray-200 px-4 py-2 rounded-md shadow-md text-sm text-gray-700">
Enter fullscreen mode Exit fullscreen mode

Better:

<div className="card-header">...</div>
Enter fullscreen mode Exit fullscreen mode

And in index.css:

@layer components {
  .card-header {
    @apply flex items-center justify-between bg-gray-200 px-4 py-2 rounded-md shadow-md text-sm text-gray-700;
  }
}
Enter fullscreen mode Exit fullscreen mode

3. Use Arbitrary Values When Necessary

Tailwind supports custom values without needing to extend the theme:

<div class="w-[432px] text-[18px] bg-[#fef08a]">
Enter fullscreen mode Exit fullscreen mode

Useful for precise design handoffs or non-standard specs.


4. Use Variants and Group Hover

Tailwind makes state and sibling styling easier:

<div class="group">
  <h2 class="text-lg group-hover:text-blue-500">Title</h2>
</div>
Enter fullscreen mode Exit fullscreen mode

5. Keep Configuration Clean

If your tailwind.config.js grows large, extract theme values, plugins, or safelists into separate files and import them.


4.6 Debugging with Tailwind

For debugging layout issues, use:

<div class="border border-red-500 bg-yellow-100 text-black">...</div>
Enter fullscreen mode Exit fullscreen mode

Also consider:


5. Utility References, FAQs, and Final Thoughts

To close things off, here’s a quick reference of commonly used utilities, answers to frequently asked questions, and a recap of what we’ve covered so far.


5.1 Common Utility Reference Tables

These cheat tables summarize core utilities grouped by category.


Typography Utilities

Class Purpose
text-xs to text-9xl Font size
font-thin to font-black Font weight
leading-tight, leading-loose Line height
tracking-tight, tracking-wide Letter spacing
text-center, text-left, text-right Text alignment

Spacing Utilities

Class Description
p-4 Padding on all sides
px-2 Padding left and right
py-6 Padding top and bottom
m-0, mt-4, mb-2 Margin utilities
space-x-4, space-y-2 Gaps between children

Layout and Display

Class Description
block, inline-block, hidden Display modes
flex, grid Enable Flexbox or CSS Grid
flex-row, flex-col Direction in flex
justify-center, items-center Align items
gap-4, grid-cols-2 Spacing and columns

Sizing and Positioning

Class Description
w-full, h-screen Full width/height
max-w-md, min-h-0 Constraints
absolute, relative, fixed Positioning
top-0, left-1/2, translate-x-1/2 Position helpers

Backgrounds and Borders

Class Description
bg-blue-500 Background color
bg-gradient-to-r, from-pink-500, to-yellow-400 Gradients
border, border-2, border-dashed Border styles
rounded, rounded-full, rounded-lg Border radius

Effects & Transitions

Class Purpose
shadow, shadow-lg Box shadow
transition, ease-in-out, duration-300 Transitions
hover:bg-blue-500 Hover state modifier
focus:outline-none, focus:ring Focus styles

Responsive Breakpoints

Prefix Minimum Width Device Target
sm: 640px Small tablets
md: 768px Tablets
lg: 1024px Laptops
xl: 1280px Desktops
2xl: 1536px Large screens

5.2 Frequently Asked Questions (FAQs)


Q: Do I still need to purge unused CSS in Tailwind v3+?

A: No. Tailwind v3+ uses JIT mode by default and only generates the classes you actually use, eliminating the need for manual purging.


Q: Can I use Tailwind with frameworks like Next.js or Nuxt?

A: Yes. Tailwind works with all major frameworks including React (CRA/Next), Vue (Vite/Nuxt), SvelteKit, Angular, and even plain HTML.


Q: Is it okay to use Tailwind with custom CSS or SCSS?

A: Yes. Tailwind is flexible. You can write additional CSS in any format, and use @apply to compose styles from utilities.


Q: Will Tailwind make my HTML bloated?

A: While HTML may appear class-heavy, the lack of separate CSS files means fewer global side-effects. It leads to more maintainable and scoped styling.


Q: What are some alternatives to Tailwind?

A: Alternatives include Bootstrap, Chakra UI, DaisyUI, ShadCN/UI, and CSS-in-JS tools like Emotion or Styled Components. However, none match Tailwind’s balance of control and productivity.


Q: Should I use Tailwind for large projects?

A: Yes. Tailwind scales well due to its utility-first paradigm, theming support, and composability with @apply. It’s used in major production apps including GitHub Copilot and Vercel’s dashboard.


5.3 Summary: What We’ve Covered

✅ How to set up Tailwind CSS with Vite
✅ Creating configuration files and writing styles
✅ Working with responsive utilities and layout systems
✅ Using dark mode, plugins, and animations
✅ Optimizing for production and deploying
✅ Integrating with component libraries
✅ Formatting with Prettier and class ordering
✅ Best practices and debugging tips


5.4 Final Thoughts

Tailwind CSS isn't just a utility framework - it’s a design system, productivity tool, and workflow enhancer in one. Whether you're building a side project, a personal portfolio, or a large production dashboard, Tailwind offers a consistent and expressive way to build modern UIs.

By pairing it with Vite, you unlock a development experience that is fast, flexible, and fully modern.

Take your time to experiment, abstract patterns using @apply, and explore Tailwind’s plugin ecosystem. Once you get used to it, you’ll likely never want to go back to traditional CSS or component libraries.

Happy building.


📬 Let’s Connect
🌐 Portfolio: paulanik.com
💼 LinkedIn: Anik Paul
🐙 GitHub: anikpaul99
📩 Email: hello@paulanik.com

Top comments (0)