Ram
Ram

Reputation: 21

Why isn't my Flask Website running CSS File?

I am trying to create a website using Flask, but while my HTML file is working, my CSS file is not working. I have tried refreshing my cache and using different lines of code others have posted on similar questions, but nothing has worked for me.

This is my current project hierarchy:

This is my current project hierarchy

I have the following line of code in my HTML file's head.

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

I got this code from a different stack overflow question too, so I am quite confused on what I am doing wrong too.

Application not picking up .css file (flask/python)

Thanks in advance!

Upvotes: 1

Views: 473

Answers (2)

user3657941
user3657941

Reputation:

I could not duplicate your problem with the following toy example:

#!venv/bin/python
from flask import Flask
from flask import render_template

app = Flask(__name__)

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

if __name__ == '__main__':
    app.run(host='0.0.0.0', debug=True)

My directory layout is

├── app.py
├── static
│   └── css
│       └── mainpage.css
├── templates
│   └── index.html
└── venv

The contents of index.html:

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

<h1>Page Heading</h1>
<p>A paragraph.</p>

</body>
</html> 

The contents of mainpage.css:

body {
  background-color: powderblue;
}
h1 {
  color: blue;
}
p {
  color: red;
}

Upvotes: 1

Neha Anand
Neha Anand

Reputation: 1

Try adding the following piece of code in the head section

<link rel="stylesheet" type="text/css" href="/static/css/mainpage.css">

Upvotes: 0

Related Questions