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

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

Posted by: admin November 29, 2017 Leave a comment

Questions:

I am rendering a template, that I am attempting to style with an external style sheet. File structure is as follows.

/app
    - app_runner.py
    /services
        - app.py 
    /templates
        - mainpage.html
    /styles
        - mainpage.css

mainpage.html looks like this

<html>
    <head>
        <link rel= "stylesheet" type= "text/css" href= "../styles/mainpage.css">
    </head>
    <body>
        <!-- content --> 

None of my styles are being applied though. Does it have something to do with the fact that the html is a template I am rendering? The python looks like this.

return render_template("mainpage.html", variables..)

I know this much is working, because I am still able to render the template. However, when I tried to move my styling code from a “style” block within the html’s “head” tag to an external file, all the styling went away, leaving a bare html page. Anyone see any errors with my file structure?

Answers:

You need to have a ‘static’ folder setup (for css/js files) unless you specifically override it during Flask initialization. I am assuming you did not override it.

Your directory structure for css should be like:

/app
    - app_runner.py
    /services
        - app.py 
    /templates
        - mainpage.html
    /static
        /styles
            - mainpage.css

Notice that your /styles directory should be under /static

Then, do this

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

Flask will now look for the css file under static/styles/mainpage.css

Questions:
Answers:

In jinja2 templates (which flask uses), use

href="{{ url_for('static', filename='mainpage.css')}}"

The static files are usually in the static folder, though, unless configured otherwise.

Questions:
Answers:

I’m pretty sure it’s similar to Laravel template, this is how I did mine.

<link rel="stylesheet" href="/folder/stylesheets/stylesheet.css" />

Referred:
CSS file pathing problem

Simple flask application that reads its content from a .html file. External style sheet being blocked?