skip to Main Content

I can’t link a css file to an html file.

I’m am using Visual Studio Code, Python and Flask to do this.

My files are like this:

templates
   home.html
   style.css
app.py

home.html

<!DOCTYPE html>
<html>
  
  <head>
    <link href='https://fonts.googleapis.com/css?family=Raleway:400, 600' rel='stylesheet' type='text/css'>
    <link href='assets/style.css' rel='stylesheet' type='text/css'/>
  </head>

  <body>
  ...
  </body>

style.css

html, body {
    margin: 0;
    padding: 0;
  }
  
header {
    background-color: #333333;
    position: fixed;
    width: 100%;
    z-index: 5;
  }
  
h1 {
  font-family: 'Times New Roman', Times, serif;
  color:cadetblue
}

app.py

from flask import Flask, render_template

app = Flask(__name__, template_folder="templates")

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

I tried using the templates folder, it didn’t work.

I tried without using the templates folder, it didn’t work.

It doesn’t raise any error, but the page just doesn’t have the css style, for example the h1 tags keep being black with the default font, and they should be blue with Times New Roman Font.

Any help would be appreciated?🙂

2

Answers


  1. In flask, your style.css file should be inside the ‘static’ folder. Then in your Html file you should link it like this:

    <link href="{{ url_for('static', filename='style.css') }}" rel="stylesheet" type="text/css"/> 
    
    Login or Signup to reply.
  2. In your code, you used assets/style.css, but there is no assets folder in templates, so the css cannot be found.
    You can connect CSS files directly in HTML files using relative paths

    <link href='style.css' rel='stylesheet' type='text/css'/>

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search