Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS Problems with Flask Web App

Tags:

python

css

flask

I can't get the CSS to output correctly - my webpages are all unstyled.

This is my link in all my templates. What am I doing wrong?

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

Is there anything special that I have to do with Flask to get it to work?

I've been trying and changing things for about half an hour but can't seem to get it right.

To sum it up: How do you do CSS with Flask - do I have to have any special python code?

like image 621
Rohit Rayudu Avatar asked Dec 07 '12 23:12

Rohit Rayudu


People also ask

Does CSS work with flask?

CSS stylesheets are considered static files. There is no interaction with their code, like there is with HTML templates. Therefore, flask has reserved a separate folder where you should put static files such as CSS, Javascript, images or other files. That folder should be created by you and should be named static.

How do I fix CSS not working?

Make sure the link tag is at the right place If you put the <link> tag inside another valid header tag like <title> or <script> tag, then the CSS won't work. The external style CAN be put inside the <body> tag, although it's recommended to put it in the <head> tag to load the style before the page content.

Where does CSS go in flask?

They are all placed under the flaskr/static directory and referenced with url_for('static', filename='...') . You can find a less compact version of style. css in the example code. Go to http://127.0.0.1:5000/auth/login and the page should look like the screenshot below.


1 Answers

You shouldn't need to do anything special with Flask to get CSS to work. Maybe you're putting style.css in flask_project/stylesheets/? Unless properly configured, such directories won't be served by your application. Check out the Static Files section of the Flask Quickstart for some more information on this. But, in summary, this is what you'd want to do:

  1. Move static files you need to project_root/static/. Let's assume that you moved stylesheets/style.css into project_root/static/stylesheets/style.css.

  2. Change

    <link ... href="/stylesheets/style.css" /> 

    to

    <link ... href="{{ url_for('static', filename='stylesheets/style.css') }}" /> 

    This tells the template parser (Jinja2) to tell Flask to find the configured static directory in your project directory (by default, static/) and return the path of the file.

    • If you really wanted to, you could just set the path as /static/stylesheets/style.css. But you really shouldn't do that - using url_for allows you to switch your static directory and still have things work, among other advantages.

And, as @RachelSanders said in her answer:

In a production setting, you'd ideally serve your static files via apache or nginx, but this is good enough for dev.

like image 158
Nathan Avatar answered Oct 23 '22 20:10

Nathan