How to import external CSS file in Flask(Python Framework)

Published on:
Last updated:

This post is also available in: 日本語 (Japanese)

When I developed desktop app with Electron and Flask, I could not import external CSS file in Flask.
So, I make a note on this post.

When handling external CSS files with Flask, create index.html at templates folder, and create CSS file at static/css folder, then import CSS file from index.html.
Folder name of templates and static are auto included by default settings(possible to change), templates and static folders name should be good, unless you have a specific reason.

Below is a sample folder structure.
Folder static/css may not exist in some cases.

├─static
│  ├─css
│  └─fonts
└─templates

The sample code imported from the external CSS file into the HTML file looks like the following.
If you can read the external CSS file safely, CSS will be reflected.

<!-- templates/index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <link rel= "stylesheet" type= "text/css" href= "{{ url_for('static',filename='css/photon.min.css') }}">    
    <title>Sample</title>
</head>
<body>
</body>
</html>

About
Kuniyoshi Takemoto is the founder of Amelt.net LLC, and editor of this blog(www.amelt.net).Learn more and follow me on LinkedIn.