Skip to main content

Setting Up Tailwind CSS 4 in Django: A Complete Guide

Learn how to integrate Tailwind CSS 4 with Django for modern, utility-first styling. This guide covers installation, configuration, and best practices for production deployment.

abhikashyap10
2 min read
Introduction to Tailwind CSS 4

Tailwind CSS 4 brings significant improvements with a new engine, better performance, and native CSS features. Integrating it with Django creates a powerful combination for building modern web applications with utility-first styling.

What's New in Tailwind 4?

  • Lightning-fast Rust-based engine
  • Native CSS cascade layers
  • Improved build times (10x faster)
  • Better IntelliSense support
  • Zero-configuration setup
Prerequisites

Before we begin, make sure you have the following installed:

  • Python 3.8+ and Django 4.0+
  • Node.js 18+ and npm
  • Basic understanding of Django templates
Step 1: Install Tailwind CSS 4

First, initialize npm in your Django project and install Tailwind CSS:

Installing Tailwind CSS 4
# Navigate to your Django project root
cd your-django-project

# Initialize npm (creates package.json)
npm init -y

# Install Tailwind CSS 4
npm install tailwindcss@next @tailwindcss/cli@next

# Install autoprefixer and postcss (recommended)
npm install -D autoprefixer postcss
Step 2: Configure Tailwind

Create a tailwind.config.js file in your project root:

tailwind.config.js configuration
/** @type {import('tailwindcss').Config} */
export default {
  content: [
    './templates/**/*.html',
    './apps/**/templates/**/*.html',
    './static/js/**/*.js',
  ],
  theme: {
    extend: {
      colors: {
        primary: {
          50: '#eff6ff',
          100: '#dbeafe',
          500: '#3b82f6',
          600: '#2563eb',
          700: '#1d4ed8',
        },
      },
      fontFamily: {
        sans: ['Inter', 'sans-serif'],
      },
    },
  },
  plugins: [],
}
Step 3: Create CSS Input File

Create a CSS file at static/css/input.css with Tailwind directives:

static/css/input.css
@import "tailwindcss";

/* Custom styles */
@layer components {
  .btn {
    @apply px-4 py-2 rounded-lg font-medium transition-colors;
  }

  .btn-primary {
    @apply bg-primary-600 text-white hover:bg-primary-700;
  }

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

@layer utilities {
  .text-balance {
    text-wrap: balance;
  }
}
Step 4: Update package.json Scripts

Add build scripts to your package.json:

package.json scripts
{
  "scripts": {
    "dev": "tailwindcss -i ./static/css/input.css -o ./static/css/output.css --watch",
    "build": "tailwindcss -i ./static/css/input.css -o ./static/css/output.css --minify"
  },
  "dependencies": {
    "@tailwindcss/cli": "^4.0.0-alpha.25",
    "tailwindcss": "^4.0.0-alpha.25"
  },
  "devDependencies": {
    "autoprefixer": "^10.4.16",
    "postcss": "^8.4.32"
  }
}
Step 5: Django Settings Configuration

Update your Django settings to handle static files properly:

Django static files configuration
# settings.py

STATIC_URL = '/static/'
STATIC_ROOT = BASE_DIR / 'staticfiles'

STATICFILES_DIRS = [
    BASE_DIR / 'static',
]

# For production
STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage' 
Step 6: Update Base Template

Include the compiled Tailwind CSS in your base template:

templates/base.html
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{% block title %}My Django App{% endblock %}</title>

    {# Tailwind CSS #}
    <link rel="stylesheet" href="{% static 'css/output.css' %}">

    {# Custom fonts #}
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
</head>
<body class="font-sans antialiased bg-gray-50">
    {% block content %}{% endblock %}
</body>
</html>
Step 7: Development Workflow

Run Tailwind in watch mode during development:

Development workflow
# Terminal 1: Run Tailwind watcher
npm run dev

# Terminal 2: Run Django development server
python manage.py runserver
Step 8: Production Deployment

For production, build and collect static files:

Production build
# Build minified CSS
npm run build

# Collect static files
python manage.py collectstatic --noinput

# Your output.css is now optimized and ready for production
Using Tailwind in Django Templates

Now you can use Tailwind utility classes in your Django templates:

Example Django template with Tailwind
{% extends "base.html" %}

{% block content %}
<div class="min-h-screen flex items-center justify-center">
    <div class="card max-w-md w-full">
        <h1 class="text-3xl font-bold text-gray-900 mb-4">
            Welcome to Django + Tailwind
        </h1>
        <p class="text-gray-600 mb-6">
            Build beautiful interfaces with utility-first CSS.
        </p>
        <button class="btn btn-primary w-full">
            Get Started
        </button>
    </div>
</div>
{% endblock %}
Advanced: Custom Components

Create reusable component classes in your CSS:

Custom component classes
@layer components {
  .form-input {
    @apply block w-full px-4 py-2 border border-gray-300 rounded-lg;
    @apply focus:ring-2 focus:ring-primary-500 focus:border-primary-500;
    @apply placeholder:text-gray-400;
  }

  .alert {
    @apply p-4 rounded-lg border;
  }

  .alert-success {
    @apply alert bg-green-50 border-green-200 text-green-800;
  }

  .alert-error {
    @apply alert bg-red-50 border-red-200 text-red-800;
  }
}
Optimizing for Performance

Performance Best Practices

  • Use PurgeCSS: Tailwind 4 automatically removes unused CSS
  • Enable compression: Configure Django to serve gzipped CSS
  • Cache static files: Use Django's caching for production
  • CDN delivery: Serve static files from a CDN
Production optimizations
# settings.py - Enable compression
MIDDLEWARE = [
    'django.middleware.gzip.GZipMiddleware',  # Add this
    # ... other middleware
]

# Cache static files for 1 year in production
if not DEBUG:
    STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage' 
Troubleshooting Common Issues

Here are solutions to common problems:

Issue: Styles Not Updating

Solution: Make sure Tailwind watcher is running (npm run dev) and you've hard-refreshed your browser (Ctrl+F5).

Issue: Classes Not Working

Solution: Check your content paths in tailwind.config.js to ensure they match your template locations.

Issue: Build Errors

Solution: Clear npm cache and reinstall: rm -rf node_modules package-lock.json && npm install

Integration with Django Forms

Style Django forms with Tailwind using widget attributes:

Styling Django forms
# forms.py
from django import forms

class ContactForm(forms.Form):
    name = forms.CharField(
        widget=forms.TextInput(attrs={
            'class': 'form-input',
            'placeholder': 'Your name'
        })
    )
    email = forms.EmailField(
        widget=forms.EmailInput(attrs={
            'class': 'form-input',
            'placeholder': 'your@email.com'
        })
    )
    message = forms.CharField(
        widget=forms.Textarea(attrs={
            'class': 'form-input',
            'rows': 4,
            'placeholder': 'Your message...'
        })
    )
Conclusion

You now have a fully functional Tailwind CSS 4 setup in your Django project! The combination provides a modern development experience with Django's robust backend and Tailwind's utility-first styling.

This setup gives you fast development, excellent performance, and a scalable architecture for building beautiful web applications.

Next Steps

  • Explore Tailwind UI components
  • Add dark mode support with Tailwind
  • Integrate HTMX with Tailwind for dynamic interactions
  • Set up automatic deployment with GitHub Actions

Share this post: