How to use tailwind in a django project

Dec 09, 2023    |   

In this tutorial, we will guide you through setting up Tailwind CSS for your Django project. Here are the steps:

1. Install Tailwind CSS and its dependencies:

Run the following commands in your project's root directory:

npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init

2. Configure Tailwind CSS:

Replace the contents of the tailwind.config.js file with the provided code.

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


Update the paths to your app's templates if needed.

3. Configure PostCSS:

Create a postcss.config.js file with the provided code.

module.exports = {
  plugins: {
    tailwindcss: {},
    autoprefixer: {},
  }
}

4. Add Tailwind directives to your CSS:

Create a static/src/input.css file and add the provided code.

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

5. Update package.json:

Add the provided "dev" script to the package.json file.

"scripts": {
    "dev": "npx tailwindcss -i ./static/src/input.css -o ./static/src/styles.css --watch"
  },

6. Update your app templates:

Add the provided link tag to the head section of your layout.html  or base.html file.

<link href="{% static 'src/styles.css' %}" rel="stylesheet">

7. Update Django settings:

Import the os module at the top of your settings.py file.

import os


Configure the STATICFILES_DIRS variable to include the static directory.

STATICFILES_DIRS = [os.path.join(BASE_DIR, "static")]

8. Run the development server:

Open a new terminal window and run the command "npm run dev".