Static Files
Web applications need CSS for styling, JavaScript for interactivity, and images for graphics. These are called static files. Flask serves them from a `static/` folder.
Creating the Static Folder
Create a folder named `static` in your project directory. Inside, you can have subfolders like `css/`, `js/`, `images/`.
Example: Adding CSS
Create `static/css/style.css`:
body { font-family: Arial; background: #f0f0f0; }
h1 { color: blue; }Link it in your HTML template:<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">Adding JavaScript
Create `static/js/script.js`:
console.log('Flask app loaded');Include in template:<script src="{{ url_for('static', filename='js/script.js') }}"></script>Adding Images
Place an image in `static/images/logo.png`. Use:
<img src="{{ url_for('static', filename='images/logo.png') }}" alt="Logo">Why Use `url_for` for Static Files?
It generates the correct URL even if your application is not at the root of the domain. It also automatically adds a cache‑busting query parameter when you change the file.
Two Minute Drill
- Static files (CSS, JS, images) go in the `static/` folder.
- Use `url_for('static', filename='path')` to generate URLs.
- Organize static files into subfolders like `css/`, `js/`, `images/`.
- This keeps your project clean and maintainable.
Need more clarification?
Drop us an email at career@quipoinfotech.com
