Include CSS File in Template in Python Flask

Flask – Include CSS file in template

In a flask application, we can have a static CSS file and include it in all templates using link HTML tag and url_for() function to point to the static CSS file.

The following is a simple code snippet for link tag with reference for a static CSS file located at css/styles.css.

<link rel="stylesheet" href="{{ url_for('static', filename='css/styles.css') }}">

url_for() with the given arguments in the above code snippet, points to css/style.css file in the static folder. The static folder must be present at the root of flask application.

Example

In this example, we build a flask application where we have following project structure.

Python flask project structure

We include the styles.css file in index.html using link tag and url_for() function.

main.py

from flask import Flask, render_template

app = Flask(__name__)

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

if __name__ == "__main__":
    app.run(host="127.0.0.1", port=8080, debug=True)

index.html

<!DOCTYPE html>
<html>
  <head>
    <link rel="stylesheet" href="{{ url_for('static', filename='css/styles.css') }}">
  </head>

  <body>
    <header>
      <h1>Flask Application</h1>
      <hr>
    </header>

    <h2>Welcome to Flask Tutorial</h1>
    <p>Welcome to sample flask application by <a href="https://pythonexamples.org/">PythonExamples.org</a>.</p>

  </body>
</html>

Run Application

Open terminal or command prompt at the root of the application, and run the Python file main.py.

Run Flask Application

The flask application is up and running at URL http://127.0.0.1:8080/.

Now, open a browser of your choice and hit the URL http://127.0.0.1:8080/.

Python Flask - Include CSS file in template

Thus we can include a static CSS file in a flask website.

Project ZIP

Summary

In this Python Flask Tutorial, we learned how to include a static CSS file in a HTML template, with the help of an example flask application.

Related Tutorials

Code copied to clipboard successfully 👍