CodingNic

Flask Fundamentals

Static Files

Flask Fundamentals 10 min read

Static Files

Static Files

Web applications are not just HTML—they also use CSS, JavaScript, and images.

Static files allow you to add styling and interactivity to your application.

What are Static Files?

Static files are files that do not change dynamically.

They include:

  • CSS files (styling)
  • JavaScript files (behavior)
  • Images

Static Folder in Flask

Flask uses a special folder called static/.

Example structure:

id="static-structure"
project/ ├── static/ │ ├── style.css │ ├── script.js │ └── image.png

Flask automatically serves files from this folder.

Using Static Files in Templates

You link static files using url_for:

id="static-link"
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">

This ensures Flask correctly finds your files.

How It Works

  • Flask receives a request for a static file
  • It looks in the static/ folder
  • It returns the file to the browser

Static Files Flow

Why Static Files Matter

Static files allow you to:

  • Style your application with CSS
  • Add interactivity with JavaScript
  • Display images and assets

Without them, your app would be plain and limited.

Best Practices

  • Organize files into folders (css/, js/, images/)
  • Use meaningful filenames
  • Avoid mixing static files with backend code

Challenge

Add styling to your app.

What to do

  1. Create a folder called static/

  2. Inside it, create a file style.css

  3. Add simple styles:

    • Change background color
    • Change text color
  4. Link the CSS file in your HTML template using url_for

  5. Add an image inside the static/ folder

  6. Display the image in your template

What you should see

  • Your page has styling applied
  • The image appears correctly

Summary

  • Static files include CSS, JavaScript, and images
  • Flask serves them from the static/ folder
  • They are linked using url_for

In the next lesson, you’ll learn how to handle forms and user input.