In this article we want to learn How to Connect HTML CSS with Python, so as you know in today’s world, web development is one of the important part of industries, and also Python is one of the popular programming languages that offers different ways to connect HTML and CSS for creating dynamic and interactive web pages.
First of all, you need to have some information about HTML, CSS, and Python because the main concept of this article is how we can combine HTML, CSS, and Python.
Now let’s talk that how we can combine these technologies, so Python allows you to generate dynamic content and manipulate HTML elements. for combining Python with your HTML template, you can use templating engines such as Flask or Django. In this example, we want to use Flask, It is a lightweight web framework in Python programming language.
First of all we need to install Flask and you can use pip for that.
1 |
pip install flask |
After that we need to import the Flask module and create an instance of the Flask class in our Python code:
1 2 |
from flask import Flask app = Flask(__name__) |
Define a route in your Python code to handle requests to the root URL (“/”) and return the rendered HTML template:
1 2 3 |
@app.route("/") def home(): return render_template("index.html") |
And lastly, add the following code to run the Flask application:
1 2 |
if __name__ == "__main__": app.run() |
For adding dynamic content to the web page, we can pass variables from our Python code to the HTML template.
1 2 3 4 |
@app.route("/") def home(): name = "Geekscoders.com" return render_template("index.html", name=name) |
In your HTML template, you can now access the name variable using templating syntax:
1 |
<h1>Hello, {{ name }}</h1> |
This is the complete code for app.py file
1 2 3 4 5 6 7 8 9 10 11 12 13 |
# app.py from flask import Flask, render_template app = Flask(__name__) @app.route("/") def home(): name = "Geekscoders.com" return render_template("index.html", name=name) if __name__ == "__main__": app.run(debug=True) |
Create a folder at name of templates and add index.html file in that folder, in the this we have also linked our CSS file.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<!-- index.html --> <!DOCTYPE html> <html> <head> <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='styles.css') }}"> </head> <body> <h1>Hello, {{ name }}</h1> <p>Welcome to my website.</p> </body> </html> |
This is our style.css file, make sure that you have created a static folder and added this file in there.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
/* styles.css */ body { background-color: #f0f0f0; font-family: Arial, sans-serif; } h1 { color: #333; font-size: 24px; margin-bottom: 10px; } p { color: green; font-size: 16px; } |
Run the complete code and this will be the result
