Introduction
Hey there, aspiring Flask developers! So, you’ve learned the basics of Flask, you’ve built a basic app (maybe a to-do list, a blog, or a cute little weather app), but now you want to make it look good. You’ve heard of Tailwind CSS, and you’re wondering, "How can I use it with my Flask app?" Well, don't worry, you're in the right place!
In this blog, we’re going to take a fun and easy approach to integrating Tailwind CSS into your Flask application. By the end, you'll be styling your Flask apps like a pro (and maybe impress your friends with your snazzy code). Let's dive in, shall we?
What’s Tailwind CSS? Why Should I Care?
Before we dive into the setup, let’s take a moment to understand what Tailwind CSS is and why it’s such a game changer.
Tailwind CSS is a utility-first CSS framework. What does that mean? Well, instead of giving you pre-designed components (like buttons or navbars) that you have to customize, Tailwind provides you with small, reusable utility classes. These classes are like tools in a toolbox. For example, bg-blue-500
sets the background color, text-center
aligns text in the middle, and py-2
adds vertical padding. You combine these simple classes directly in your HTML to style your elements.
This approach gives you more control over your design without needing to write a bunch of custom CSS or struggle with complex class names.
Why does this matter for you? If you’re building a Flask app, Tailwind allows you to quickly make your app look great with minimal effort. You don’t have to spend time worrying about the stylesheets or reinventing the wheel with custom designs. Instead, you can just apply the classes you need and get a polished look in no time.
In short, Tailwind lets you style your app efficiently without writing too much custom CSS, so you can focus more on building your app’s functionality. Sounds great, right?
Step 1: Set Up Your Flask App (If You Haven’t Already)
If you don’t have a Flask app yet, don’t sweat it. Here’s a quick refresher. Open your terminal, and let’s get started!
1. First, create a folder for your project:
mkdir flask-tailwind
cd flask-tailwind
2. Then, create a virtual environment
If you’ve worked with React or Node before, you’re probably familiar with how dependencies are stored in the node_modules
folder. This keeps everything neat and specific to your project, preventing conflicts with other projects.
Python works a bit differently. Instead of having a node_modules
or python_modules
folder, dependencies are installed globally by default. This can lead to a mess if different projects require different versions of the same package.
To avoid this, Python lets you create a virtual environment—think of it like a separate, isolated room for your project. Inside this room, you can install only the dependencies your project needs, keeping everything tidy and preventing conflicts with other projects. So let us create one:
python3 -m venv .venv
3. Activate the virtual environment:
Now that we’ve created our virtual environment—our private room for project dependencies—let’s tell Python we’re ready to use it. It’s like unlocking the door to our room and stepping inside. To activate the environment, just run the following command:
- On Windows ( like CMD or PS ):
.venv\Scripts\activate
- On windows (Git bash):
source .venv/Scripts/activate
- On macOS/Linux:
source .venv/bin/activate
4. Install Flask (if you haven’t installed it already):
pip install flask
5. Create a basic Flask app structure like this:
flask-tailwind/
├──.venv/
├── templates/
│ └── index.html
├── static/
│ └── css/
└── app.py
And that's it for the Flask app setup! Let’s move on to adding Tailwind.
Step 2: Install Tailwind CSS with Flask
Alright, here’s where the magic happens. We’re going to make your Flask app look great using Tailwind. Don’t worry, it’s easier than it sounds.
Installing Tailwind Using NPM (Node Package Manager)
Even though Flask is Python-based, we need a tool from the JavaScript world—npm (Node Package Manager). NPM helps us install Tailwind and manage our dependencies.
- First, install Node.js and npm if you haven’t already. You can download Node.js from here.
- Now, inside your Flask project folder (where
app.py
is), run this command to initialize a package.json file:
npm init -y
This will create a package.json
file, which helps npm manage your packages.
3. Next, let’s install Tailwind CSS
npm install -D tailwindcss
npx tailwindcss init
After the installation, create a tailwind.config.js file by running:
npx tailwindcss init
This generates a file that looks like this:
/** @type {import('tailwindcss').Config} */
module.exports = {
content: [],
theme: {
extend: {},
},
plugins: [],
}
In the content
property include where you will use tailwindcss like:
/** @type {import('tailwindcss').Config} */
module.exports = {
content: [ "./templates/**/*.html"],
theme: {},
plugins: [],
}
We’ll keep the default settings for now, but you can customize this file later if you need it.
But Wait—npm
? I Thought This Was Flask!
Ah, I hear you! You might be thinking, “Wait a minute, I thought Flask was all about Python? Why am I using npm and Node.js for styling? Isn’t that a React/Next.js thing?”
First off, I get it. If you’re used to working in the pure Python world, throwing in some JavaScript-based tools like npm and Tailwind CSS might seem a little weird. You might be wondering, "What if I need to deploy this app in the future? Does this npm
stuff complicate things? What if I have to deal with npm build
nonsense when deploying?"
Let me put your mind at ease! 🧘♂️
Flask is great because it’s flexible, and you can keep it as simple or as complex as you want. The use of npm here is only for the front-end—just to handle the styling part with Tailwind CSS. Flask will still be your Python-based server, running and managing the logic. You're not throwing away Flask for a JavaScript ecosystem; you're just making the front-end side more modern and easier to handle.
Don’t Worry About Future Deployments
When it comes time to deploy your app, Flask doesn’t care about the npm
setup. Here’s why:
- No NPM at Runtime: During runtime, your Flask app just serves the CSS and HTML that has already been processed by Tailwind. The final result is a simple static CSS file that Flask can serve as any other static asset. No
npm
required when you’re running the app in production. - Build Process Is a One-Time Thing: The
npm
command to build Tailwind is only for development and building your styles. Once you’ve processed your Tailwind CSS into a final output file (usuallyoutput.css
), Flask will just serve it like a normal CSS file. No need to worry aboutnpm build
in production! - Deploying Like a Flask App: Whether you deploy to Heroku, DigitalOcean, or your own server, it’s just a Flask app with some CSS on the side. You can deploy it exactly the same way you would deploy any regular Flask app—there’s no special handling for the Tailwind setup after the build.
- Static Assets Are Safe: Tailwind’s utility classes are pre-built and bundled up into that final
output.css
file. When it’s time to deploy, that’s all you need. No runtime dependencies onnpm
or JavaScript.
So, no worries about “npm” getting in the way of your Flask app or adding complexity to your deployment process. It’s just a tool for getting your styles looking good—after that, it’s pure Python. 🍰
Now, go ahead and style your Flask app without any stress. Tailwind and Flask go together like peanut butter and jelly—without the sticky mess!
Create the Tailwind CSS Input File
Now, we need to create the CSS file where Tailwind’s magic will happen.
- Inside your static/css folder, create a new file named
tw.dev.css
. - In
tw.dev.css
, add the following lines:
@tailwind base;
@tailwind components;
@tailwind utilities;
These directives tell Tailwind to add its base styles, component styles, and utility classes.
Step 3: Build Your Tailwind CSS
At this point, you’ve got everything set up, but we need to process the Tailwind CSS and make it ready for use in your app.
- In your terminal, run the following command to process the CSS:
npx tailwindcss -i ./static/css/tw.dev.css -o ./static/css/tw.css --watch --minify
-i
specifies the input file (styles.css
).-o
specifies the output file (output.css
).--watch
keeps the process running and watches for changes.--minify
reduces the size of the finaloutput.css
by removing unnecessary whitespaces and line breaks.
HEADS UP
If you're curious, "tw" is short for Tailwind!
This will create an tw.css
file in the static/css
folder. This is the file you will link in your HTML template.
Step 4: Link Tailwind CSS in Your Flask Templates
Now, let’s connect the tw.css
file to your Flask templates so the styles are applied.
- Open the index.html file inside the templates/ folder, and add the following inside the
<head>
section:
<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/tw.css') }}" rel="stylesheet">
</head>
<body class="bg-gray-100 text-gray-900">
<h1 class="text-4xl text-center font-bold py-10">Hello, Flask with Tailwind!</h1>
<p class="text-center">Tailwind is working!</p>
</body>
</html>
Flask’s url_for
function helps us link to the static files. This will point to the output.css file that was generated earlier.
🎉 Done
Now you can start using Tailwind classes in your templates to style your Flask app.
Step 5: Run Your Flask App
Finally, let's start your Flask app and see Tailwind in action.
- In app.py, add the following code:
from flask import Flask, render_template
app = Flask(__name__, templates_folder="templates", static_folder="static", static_url_path="/")
@app.route('/')
def home():
return render_template('index.html')
if __name__ == '__main__':
app.run(debug=True)
Run your Flask app by executing:
python3 app.py
Open your browser and go to http://127.0.0.1:5000/
You should see your page styled with Tailwind CSS!
Conclusion
And there you have it! You've just integrated Tailwind CSS with your Flask app. 🎉 Now, your app is not only functional but looks sleek too!
Tailwind allows you to quickly and easily build beautiful user interfaces without the headache of writing custom CSS. It’s the perfect companion for Flask, especially when you’re just getting started and want something simple and effective.
So, go ahead, experiment, make your Flask apps even more stylish, and keep learning! With Flask and Tailwind, the sky’s the limit!
And if you ever get stuck or need a break from all the code, just remember—coffee and coding go hand in hand. 😉