Перейти к содержимому
Web Development

Tailwind CSS for Django: Why We Use It and How to Set It Up

Ruslan Danelian 7 мин чтения
Скопировано!
Tailwind CSS for Django: Why We Use It and How to Set It Up

Every Django project I build uses Tailwind CSS. Not because it is popular — because it solves a real problem: keeping styles consistent across dozens of Django templates without a growing custom CSS file that nobody wants to touch.

This guide covers how to set up Tailwind CSS 4 with Django and Vite, why utility-first CSS fits Django's template system well, and practical patterns for theming, dark mode, and production builds.

Need help with custom web development? I provide custom web development for businesses ready to grow. Learn about my custom web development service or get in touch for a free consultation.

Key Takeaways
  • Understand why Tailwind works for Django projects
  • Setup: Tailwind CSS 4 + Django + Vite
  • Production build and deployment
  • Common objections

Why Tailwind works for Django projects

Django templates are component-like but not components. You have {% include %} partials, {% block %} inheritance, and template tags — but no scoped styles. In a project with 50+ templates, traditional CSS approaches break down:

  • BEM naming conventions become a naming exercise that adds no value when you have 200 classes
  • Component CSS files require a build system to scope and bundle them
  • Inline styles cannot handle hover states, responsive breakpoints, or dark mode

Tailwind's utility classes solve this. The style lives next to the HTML element, moves with the template partial, and needs no naming. When you delete a template, the styles go with it. No dead CSS to clean up.

Setup: Tailwind CSS 4 + Django + Vite

🧭 Illustration: step-by-step process diagram for Setup: Tailwind CSS 4 + Django + Vite
Visual guide: Setup: Tailwind CSS 4 + Django + Vite

Tailwind CSS 4 simplified the setup significantly. No more tailwind.config.js for basic usage — configuration happens in CSS.

Step 1: Install dependencies

npm init -y
npm install -D vite tailwindcss @tailwindcss/vite django-vite

Step 2: Create Vite config

// vite.config.js
import { defineConfig } from "vite";
import tailwindcss from "@tailwindcss/vite";

export default defineConfig({
  plugins: [tailwindcss()],
  build: {
    outDir: "static/dist",
    manifest: "manifest.json",
    rollupOptions: {
      input: "static/src/js/main.js",
    },
  },
});

Step 3: Create CSS entry point

/* static/src/css/main.css */
@import "tailwindcss";

@source "../../templates/**/*.html";

@theme {
  --color-brand: #6d28d9;
  --color-ink: #1c1917;
  --color-graphite: #57534e;
  --color-cloud: #f5f5f4;
  --font-heading: "Archivo", system-ui, sans-serif;
  --font-body: "Newsreader", Georgia, serif;
}

Step 4: JavaScript entry point

// static/src/js/main.js
import "../css/main.css";

Step 5: Django settings

# config/settings/base.py
INSTALLED_APPS = [..., "django_vite"]
DJANGO_VITE = {
    "default": {
        "dev_mode": env.bool("VITE_DEV_MODE", False),
        "dev_server_host": "localhost",
        "dev_server_port": 5173,
        "manifest_path": BASE_DIR / "static" / "dist" / "manifest.json",
    }
}

Step 6: Base template

{% load django_vite %}
<head>
  {% vite_hmr_client %}
  {% vite_asset "static/src/js/main.js" %}
</head>

Running

# Terminal 1: Django
DJANGO_ENV=dev python manage.py runserver 8005

# Terminal 2: Vite (HMR)
npm run dev

# Production build
npm run build

In a project with 50+ templates, traditional CSS approaches break down:

Practical patterns for Django templates

Template partials stay self-contained

A Django partial like includes/post_card.html carries its full styling:

<article class="rounded-lg border border-cloud bg-white p-5 shadow-sm">
  <h3 class="font-heading text-lg font-bold text-ink">{{ post.title }}</h3>
  <p class="mt-2 font-body text-sm text-graphite">{{ post.excerpt }}</p>
</article>

Move this partial to another template, and the styles come with it. No CSS imports to update, no class name collisions.

Dark mode with system preference + toggle

Tailwind's dark: variant works well with Django's template system. The pattern I use across all projects:

/* CSS: system preference as default */
@custom-variant dark (&:where(.dark, .dark *));

/* JS: theme toggle persisted to localStorage */
<!-- Template: dark mode classes -->
<body class="bg-white text-ink dark:bg-zinc-900 dark:text-stone-200">
  <h1 class="text-brand dark:text-violet-400">{{ title }}</h1>
</body>

Store the user's choice in localStorage and apply a .dark class to <html> before the page renders to avoid flash.

Responsive layouts without media query CSS

<div class="grid gap-6 sm:grid-cols-2 lg:grid-cols-3">
  {% for service in services %}
    <div class="rounded-lg border p-6">...</div>
  {% endfor %}
</div>

One line handles mobile (1 column), tablet (2 columns), and desktop (3 columns). No separate media query blocks to maintain.

Design tokens in CSS

Tailwind CSS 4's @theme directive replaces the old config file. Define your brand colors, fonts, and spacing once:

@theme {
  --color-brand: #6d28d9;
  --color-brand-light: #ede9fe;
  --color-ink: #1c1917;
  --color-graphite: #57534e;
  --color-cloud: #f5f5f4;
  --font-heading: "Archivo", system-ui, sans-serif;
  --font-body: "Newsreader", Georgia, serif;
  --radius-card: 0.5rem;
}

Then use them as text-brand, font-heading, rounded-card throughout templates. Change the token value, and every usage updates.

Pro Tip

The pattern I use across all projects: Store the user's choice in localStorage and apply a .dark class to <html> before the page renders to avoid flash.

Production build and deployment

npm run build produces a hashed manifest in static/dist/. Django-vite reads the manifest and generates correct <script> and <link> tags with cache-busting hashes.

The build output is small. Tailwind only includes the utilities your templates actually use. A typical Django project produces 15-30KB of CSS (gzipped), regardless of how many utility classes exist in the framework.

Deployment workflow:

  1. npm run build locally
  2. Rsync static/dist/ to VPS
  3. python manage.py collectstatic --clear
  4. Restart gunicorn

See my Django VPS deployment guide for the full process, and site speed optimization for Tailwind-specific performance tips.

Want expert help with this? Let's make it happen.

Get a Free Consultation

Common objections

🎯 Illustration: diagram illustrating Common objections
Visual guide: Common objections

"The HTML looks messy"

It looks different, not messy. You trade a CSS file you have to cross-reference with HTML for self-documenting HTML. After a week of Tailwind, reading mt-4 text-sm text-graphite is faster than finding .card-subtitle in a stylesheet.

"What about reusable styles?"

Django partials are your reusable styles. {% include "includes/button.html" with variant="primary" %} is a component. @apply exists for the rare case where you need a CSS class, but reaching for it often means you should make a template partial instead.

"It's hard to override for different sections"

Use CSS custom properties (design tokens) for section theming. The marketing section can redefine --color-brand without touching template classes.

Related reading: React vs Django Templates: When to Add a JavaScript Frontend · Django vs WordPress: Which Is Better for Your Business Website · Modernizing Legacy Django: From 2.x to 6.1 Without a Rewrite

Frequently asked questions

Is Tailwind CSS good for Django projects?

Yes — it fits Django's template system better than most CSS approaches. Styles stay with template partials, there is no naming overhead, dark mode and responsive design are built in, and the production output is small. I use it on every Django project I build.

How do I set up Tailwind CSS 4 with Django?

Install Vite and the Tailwind CSS Vite plugin, create a CSS entry point with @import "tailwindcss", point it at your templates with @source, and use django-vite to load assets in your base template. The setup takes about 15 minutes.

Does Tailwind CSS slow down Django page loads?

No. Tailwind's production build only includes classes your templates use — typically 15-30KB gzipped. That is smaller than most custom CSS files. The Vite build adds cache-busting hashes for optimal browser caching.

Can I use Tailwind CSS without Vite in Django?

Yes — the Tailwind CLI standalone build works without Node.js. However, Vite adds hot module replacement in development (instant style updates without page reload) and handles JavaScript bundling if you need it. For projects already using npm, Vite is the better choice.

Should I use Tailwind or Bootstrap for a Django project?

Tailwind if you want full design control and are comfortable with utility classes. Bootstrap if you want pre-built components and are fine with the Bootstrap look. For custom designs — which most client projects require — Tailwind is significantly more flexible.

Ruslan Danelian
Ruslan Danelian

Full-stack разработчик, специализирующийся на Django, ИИ-автоматизации и управлении Google Ads. Создаю production SaaS платформы и кастомные веб-приложения для бизнеса по всей территории США.

Читайте далее

Есть ли у вас проект в планах?

Расскажите, что вам нужно. В течение одного рабочего дня я пришлю план со сроками и фиксированной стоимостью.

Year-end offer

20% off AI tools & custom CRM

AI chat assistants, DM bots, lead scoring and a CRM built around your business.

Claim 20% off