CSS Problems with Flask Web App
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:
Move static files you need to
project_root/static/
. Let's assume that you movedstylesheets/style.css
intoproject_root/static/stylesheets/style.css
.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 - usingurl_for
allows you to switch your static directory and still have things work, among other advantages.
- If you really wanted to, you could just set the path as
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.
4 steps to do this (building a lot on some of the other answers here, presuming you've got Flask all set up properly):
1) Create a static folder in your app
folder:[root_folder]/app/static/
2) Move all of your static content (images, JavaScript, CSS, etc.) into those folders. Keep the content in their respective folders (not mandatory, just neater and more organized).
3) Modify your __init__.py
file in the app
folder to have this line:
app.static_folder = 'static'
This will allow your app to identify your static
folder and read it accordingly.
4) In your HTML, set up your file links as such:
<link ... href="{{ url_for('static', filename='[css_folder]/[css-file].css') }}" />
For example, if you call your CSS folder 'stylesheets' and file 'styles':
<link ... href="{{ url_for('static', filename='stylesheets/styles.css') }}" />
That should set everything up properly. Good luck!