In a Flask app, you want to add a CSS file to style your pages. Where should you place the CSS file so Flask can serve it automatically?
Flask has a special folder for static files like CSS and images.
Flask automatically serves files placed in the static folder. This is the default folder for static assets like CSS, JavaScript, and images.
You have a CSS file named style.css inside the static folder. Which HTML line correctly links this CSS file in a Flask Jinja2 template?
Use Flask's url_for function to generate URLs for static files.
Using {{ url_for('static', filename='style.css') }} ensures the correct URL is generated for the CSS file, even if the app is deployed with a prefix or different static folder.
Consider this Flask app structure:
project/
├── app.py
├── static/
│ └── main.css
└── templates/
└── index.htmlIn index.html, the CSS is linked as:
<link rel="stylesheet" href="/main.css">
Why does the CSS not load when you open the page?
Static files are served from the /static/ URL path by default.
Flask serves static files from the /static/ URL path. Linking to /main.css misses the static prefix, so the file is not found.
Given a Flask app with a CSS file theme.css inside the static folder, what URL does this Jinja2 code generate?
{{ url_for('static', filename='theme.css') }}By default, Flask serves static files under the /static/ URL path.
The url_for('static', filename='theme.css') generates the URL /static/theme.css which points to the CSS file inside the static folder.
You want to serve CSS files from a folder named assets instead of the default static folder in Flask. Which approach correctly configures Flask to serve CSS files from assets?
Flask's constructor accepts a static_folder parameter to change the static files folder.
Passing static_folder='assets' to Flask changes the folder Flask uses to serve static files. Then CSS files placed inside assets are served at /static/ URL by default.