0
0
Flaskframework~30 mins

Serving CSS files in Flask - Mini Project: Build & Apply

Choose your learning style9 modes available
Serving CSS files in Flask
📖 Scenario: You are building a simple Flask web app that needs to show a styled homepage. To do this, you will serve a CSS file from a static folder and link it in your HTML template.
🎯 Goal: Build a Flask app that serves a CSS file correctly and applies styles to the homepage.
📋 What You'll Learn
Create a Flask app with a route for the homepage
Create a CSS file inside a static folder
Link the CSS file in the HTML template using url_for('static', filename='style.css')
Serve the homepage with the CSS styles applied
💡 Why This Matters
🌍 Real World
Web developers often need to serve CSS files to style their web pages. Flask's static folder and url_for function make this easy.
💼 Career
Knowing how to serve static files like CSS is essential for backend developers working with Flask to build web applications.
Progress0 / 4 steps
1
Create the Flask app and homepage route
Create a Flask app by importing Flask and instantiate it as app. Then create a route for '/' that returns the string 'Hello, Flask!'.
Flask
Need a hint?

Start by importing Flask and creating an app instance. Then use @app.route('/') to define the homepage function.

2
Create the CSS file in the static folder
Create a folder named static in your project. Inside it, create a file named style.css with the exact content: body { background-color: lightblue; }
Flask
Need a hint?

Create a folder named static next to your Python file. Inside it, create style.css with the background color style.

3
Link the CSS file in the HTML returned by the route
Modify the home function to return an HTML string that includes a <link> tag in the <head> section. Use url_for('static', filename='style.css') to set the href attribute of the <link> tag. The HTML should have a <h1> with text Welcome to Flask inside the <body>.
Flask
Need a hint?

Use a multi-line string with f"""...""" and insert the CSS link using url_for('static', filename='style.css').

4
Run the Flask app with debug mode
Add the if __name__ == '__main__': block at the end of the file. Inside it, call app.run(debug=True) to start the Flask app with debug mode enabled.
Flask
Need a hint?

Use the standard Python entry point check and call app.run(debug=True) inside it.