🎓 A1Learner
🔍
0 of 50 lessons completed

Styling Flask Pages

A page links its CSS with a link tag. The href comes from url_for, so the address stays right.

Write the CSS file

This code writes style.css into the static folder.

import os

os.makedirs("static", exist_ok=True)
with open("static/style.css", "w") as f:
    f.write("h1 { color: blue; }")

Link the CSS in a page

The view renders a page with a link tag. The href comes from url_for, so it points at the CSS file.

from flask import Flask, url_for, render_template_string

app = Flask(__name__)

@app.route("/")
def home():
    return render_template_string('<link rel="stylesheet" href="{{ css }}"><h1>Hi</h1>', css=url_for("static", filename="style.css"))

Ask for the styled page

The test client asks for / and prints the page with the link tag in it.

client = app.test_client()
print(client.get("/").data.decode())

Example

import os

os.makedirs("static", exist_ok=True)
with open("static/style.css", "w") as f:
    f.write("h1 { color: blue; }")

from flask import Flask, url_for, render_template_string

app = Flask(__name__)

@app.route("/")
def home():
    return render_template_string('<link rel="stylesheet" href="{{ css }}"><h1>Hi</h1>', css=url_for("static", filename="style.css"))

client = app.test_client()
print(client.get("/").data.decode())

Key points

  • A <link> tag loads a CSS file into a page.
  • rel="stylesheet" says the file is CSS.
  • The href holds the address of the CSS file.
  • url_for builds the href from the static folder.

In this example, style.css is written into the static folder first. The view renders a page with a link tag, and the href comes from url_for. The test client asks for / and prints the page with the link tag in it.

Note

The CSS file lives in static, not in templates.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does the href of a CSS link tag hold?