0
0
Flaskframework~5 mins

Serving CSS files in Flask

Choose your learning style9 modes available
Introduction

We use CSS files to style web pages. Serving CSS files means making them available to the browser so the page looks nice.

You want to add colors, fonts, or layouts to your Flask web page.
You have multiple pages that share the same style and want to keep CSS separate.
You want to improve page load speed by letting browsers cache CSS files.
You want to organize your project by keeping CSS files in a special folder.
You want to update styles without changing HTML code.
Syntax
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').

Examples
This HTML line links a CSS file named style.css from the static folder.
Flask
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
Folder structure showing where to put CSS and HTML files.
Flask
project_folder/
  static/
    style.css
  templates/
    index.html
  app.py
Example of a simple HTML template linking a CSS file served by Flask.
Flask
<!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>
Sample Program

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/.

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)
OutputSuccess
Important Notes

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.

Summary

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.