Web Development

TailwindCss for Flask

A Guide to Using Tailwind CSS in Flask

J
Johnathon_Crowder

December 13, 2024

8 min read 3 tags
TailwindCss for Flask

 Flask is a powerful web framework, but when it comes to styling your web applications, it’s often a good idea to incorporate a utility-first CSS framework like Tailwind CSS. Tailwind offers a highly customizable, easy-to-use solution for quickly building aesthetically pleasing user interfaces without writing a ton of custom CSS.

In this guide, we’ll walk through how to integrate Tailwind CSS with your Flask application step by step.

Why Use Tailwind CSS?

Before jumping into the integration, let’s quickly review why Tailwind CSS is a great choice for web developers:

  • Utility-first design: Instead of writing custom CSS for every component, you use utility classes to style elements directly in your HTML. This makes development faster and more modular.
  • Highly customizable: Tailwind is easy to customize using its configuration file, allowing you to set up colors, spacing, fonts, and more based on your project’s requirements.
  • Responsive and mobile-first: Tailwind has built-in responsive design utilities that make building mobile-first, responsive applications straightforward.

With that out of the way, let’s dive into how to set it up in your Flask app.

Prerequisites

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

  • Python (>=3.7)
  • Flask: You can install Flask via pip if you don’t have it yet:
bash

Copy code
pip install Flask
  • Node.js: Tailwind CSS relies on Node.js for building and compiling styles, so you'll need to have it installed. You can download it from here.
  • npm: npm is the package manager for Node.js and will be used to install Tailwind CSS and related tools.

Step 1: Set Up a Flask Project

First, let's create a basic Flask application if you don’t have one already. Open your terminal and create a new project directory:

bash

Copy code
mkdir flask-tailwind-example
cd flask-tailwind-example
python -m venv venv
source venv/bin/activate  # On Windows use `venv\Scripts\activate`
pip install Flask

Create the following file structure:

graphql

Copy code
flask-tailwind-example/
│
├── app.py          # The main Flask app
├── static/         # Directory for static files like CSS, JS
│   └── css/        # Where Tailwind-generated CSS will go
├── templates/      # HTML templates
│   └── index.html  # A basic template
└── tailwind.config.js  # Tailwind configuration file

In app.py, add a basic Flask route:

python

Copy code
from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

if __name__ == '__main__':
    app.run(debug=True)

Step 2: Install Tailwind CSS

With your Flask app set up, let’s move on to installing Tailwind CSS using npm.

  1. Initialize npm: In the root directory of your project (flask-tailwind-example), run:
bash

Copy code
npm init -y
  1. This will generate a package.json file in your project folder.
  2. Install Tailwind CSS: Run the following command to install Tailwind CSS and its dependencies:
bash

Copy code
npm install -D tailwindcss postcss autoprefixer
  1. This command installs:
  • tailwindcss: the Tailwind CSS framework.
  • postcss: a tool for transforming CSS with JavaScript plugins.
  • autoprefixer: a plugin that automatically adds vendor prefixes to CSS for cross-browser compatibility.
  1. Generate Tailwind Configuration Files: After installing the dependencies, run the following to generate the tailwind.config.js and postcss.config.js files:
bash

Copy code
npx tailwindcss init
  1. This will create a tailwind.config.js file that you can use to customize Tailwind’s defaults if necessary.

Step 3: Set Up Tailwind CSS with Flask

Now that Tailwind is installed, let’s configure it to generate the CSS and serve it to your Flask app.

  1. Create the tailwind.config.js file: In the tailwind.config.js file, set up the content option to specify which files Tailwind should scan for class names:
js

Copy code
module.exports = {
  content: [
    './templates/**/*.html',  // Scan HTML files in the templates folder
    './static/js/**/*.js',    // Scan JS files in the static/js folder (if you use them)
  ],
  theme: {
    extend: {},
  },
  plugins: [],
};
  1. Create the Tailwind CSS File: Next, create a src/styles.css file inside your project directory to import Tailwind’s utility classes.
  2. Create a file called src/styles.css and add the following:
css

Copy code
/* src/styles.css */
@tailwind base;
@tailwind components;
@tailwind utilities;
  1. This imports the base styles, component classes, and utility classes that Tailwind provides.
  2. Configure PostCSS: Create the postcss.config.js file in the root of your project, which tells PostCSS to use Tailwind and Autoprefixer. Add the following:
js

Copy code
module.exports = {
  plugins: [
    require('tailwindcss'),
    require('autoprefixer'),
  ],
};

Step 4: Build Tailwind CSS

Now that we’ve set everything up, it’s time to generate the compiled CSS file that Tailwind will use.

  1. Create a Build Script: Add a build script to your package.json to automate the process of generating the compiled CSS. Open your package.json file and add the following under "scripts":
json

Copy code
"scripts": {
  "build": "tailwindcss build src/styles.css -o static/css/tailwind.css",
  "watch": "tailwindcss build src/styles.css -o static/css/tailwind.css --watch"
}
  • build will generate the final CSS file in static/css/tailwind.css.
  • watch will monitor changes to your source files and automatically rebuild the CSS.
  1. Build Tailwind CSS: Run the build command to generate the tailwind.css file:
bash

Copy code
npm run build
  1. You should now see a tailwind.css file in the static/css directory.

Step 5: Link the CSS File in Flask Templates

In your templates/index.html file, link the generated tailwind.css file from the static folder:

html

Copy code
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Flask + Tailwind</title>
  <link href="{{ url_for('static', filename='css/tailwind.css') }}" rel="stylesheet">
</head>
<body class="bg-gray-100 text-gray-800">

  <div class="container mx-auto p-4">
    <h1 class="text-3xl font-bold text-center">Welcome to Flask + Tailwind!</h1>
    <p class="mt-4 text-center">This is a simple Flask app styled with Tailwind CSS.</p>
  </div>

</body>
</html>

Step 6: Run Your Flask Application

With everything set up, you can now run your Flask app:

bash

Copy code
python app.py

Open your browser and go to http://127.0.0.1:5000/. You should see your Flask app styled with Tailwind CSS!

Step 7: Optional — Using Tailwind CSS in Development

If you want to automatically rebuild your CSS while you work, you can use the npm run watch command in a separate terminal window. This will rebuild your CSS whenever you make changes to your Tailwind classes:

bash

Copy code
npm run watch

Conclusion

Integrating Tailwind CSS into your Flask application is relatively simple, and it can dramatically improve your workflow when it comes to styling. By following this guide, you’ve learned how to set up Tailwind CSS with Flask, how to configure the build process, and how to style your templates using Tailwind’s utility-first approach.

Tailwind CSS is powerful, flexible, and highly customizable, which makes it an excellent choice for building modern web applications. Now you can build beautiful, responsive user interfaces with Flask and Tailwind, without writing tons of custom CSS!

Tags

Flask SoftwareDevelopment TailwindCSS
J

Johnathon_Crowder

Technical Writer & Developer

Author of 12 articles on Fusion_Code_Lab. Passionate about sharing knowledge and helping developers grow.

Discussion (0)

Join the discussion by logging in to your account

Log In to Comment

Related Articles

Unlocking the Power of Flask Blueprints

Unlocking the Power of Flask Blueprints

A Guide to Building Modular Applications

Read More →
AI and Programming

AI and Programming

How Artificial Intelligence is Changing the Way We Code

Read More →
Introduction to Rust Programming Language

Introduction to Rust Programming Language

Getting started with systems programming in Rust

Read More →