Simple Django with Tailwind CSS support

2024.08.04

This setup of Django and Tailwind CSS is by far the minimal and cleanest implementation possible, requiring no additional Django packages or complex configurations.

Install Tailwind CSS

yarn init
yarn add -D tailwindcss postcss autoprefixer
yarn tailwindcss init -p

This creates three important files in your project root:

  • package.json: Node.js project configuration
  • tailwind.config.js: Tailwind CSS configuration
  • postcss.config.js: PostCSS configuration

Configure Tailwind CSS

Add the following to your tailwind.config.js file:

/** @type {import('tailwindcss').Config} */
module.exports = {
  content: [
    './project-name/app-name/templates/**/*.html',
    // Add paths to other apps if necessary
  ],
  theme: {
    extend: {},
  },
  plugins: [],
};

Set up a global.css file

We need to add the Tailwind directives to your global css file.

@tailwind base;
@tailwind components;
@tailwind utilities;

/* Add your custom styles below */

Add tailwind script

In the package.json file, add the following script:

{
  "scripts": {
    "dev": "yarn run tailwindcss -i ./project-name/static/global.css -o ./static/styles.css --watch",
    "build": "yarn run tailwindcss -i ./project-name/static/global.css -o ./static/styles.css --minify"
  }
}

Configure Django Settings

Update your Django settings to include the static files configuration:

STATIC_URL = '/static/'
STATICFILES_DIRS = [
    BASE_DIR / "static",
]
STATIC_ROOT = BASE_DIR / "staticfiles"

Create Directory Structure

Ensure you have the following directory structure:

your-project/
├── manage.py
├── project-name/
│   ├── static/
│   │   └── global.css # Global CSS file
│   └── ...
├── static/
│   └── styles.css  # Generated file
├── package.json
├── tailwind.config.js
└── postcss.config.js

Include CSS in Templates

Add the following to your base template (e.g., 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 %}{% endblock %}</title>
    <link href="{% static 'styles.css' %}" rel="stylesheet">
</head>
<body>
    {% block content %}
    {% endblock %}
</body>
</html>

Develpment workflow

Run the following commands in separate terminals to start the tailwindcss watcher and Django server:

yarn dev
python manage.py runserver

Use tailwind classes in your HTML templates.

{% extends 'base.html' %}

{% block content %}
  <div class="container mx-auto px-4 py-8">
      <h1 class="text-3xl font-bold text-gray-900">
          Welcome to Django with Tailwind CSS
      </h1>
  </div>
{% endblock %}

Production workflow

When deploying to production it's good to minify the CSS file for better performance.

yarn build

This setup provides a clean, maintainable way to use Tailwind CSS with Django without any additional Django packages or complexity.