We use CSS files to style web pages. Serving CSS files means making them available to the browser so the page looks nice.
Serving CSS files in Flask
from flask import Flask, render_template app = Flask(__name__) @app.route('/') def home(): return render_template('index.html') if __name__ == '__main__': app.run(debug=True)
Place your CSS files inside a folder named static in your project root.
In your HTML templates, link CSS files using url_for('static', filename='style.css').
style.css from the static folder.<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
project_folder/
static/
style.css
templates/
index.html
app.py<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>My Flask App</title> <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}"> </head> <body> <h1>Welcome!</h1> </body> </html>
This Flask app serves an HTML page that uses a CSS file from the static folder.
Put style.css inside static/ and index.html inside templates/.
The CSS styles will apply to the page when you open http://localhost:5000/.
from flask import Flask, render_template app = Flask(__name__) @app.route('/') def home(): return render_template('index.html') if __name__ == '__main__': app.run(debug=True)
Flask automatically serves files from the static folder at the URL path /static/.
Make sure your CSS file is named correctly and placed inside the static folder.
Use browser developer tools to check if the CSS file loads correctly and styles apply.
Put CSS files in the static folder to serve them with Flask.
Link CSS in HTML using url_for('static', filename='yourfile.css').
This helps keep styles separate and your web pages look better.