Python informer

Improve your Python coding skills

Flask webserver - adding HTML and CSS

This article is part of a series on Flask.

In the previous example, our web page wasn’t a true web page at all. It was just a line of text, not HTML. A browser will display that as plain text, but you cannot format it in any way.

Flask allows us to create HTML files and use them as templates for our web pages.

Creating the HTML page

Create a basic HTML page, like this:

<html>
  <head>
  </head>
  <body>
    <h1>Home page</h1>
    <p>My first Flask site</p>
  </body>
</html>

Save this file is a folder called templates, under your working folder. Name the file index.html.

Changing the Python code

You will need to make a couple of changes to server.py. First you must import render_template from the Flask module. Change your first line to this:

from flask import Flask, render_template

Then you must change your index function to this:

@app.route('/')
def index():
    return render_template('index.html')

Here, instead of returning a string, our index() function returns the result of render_template(). This function reads is the html file index.html, and returns its content as a string. Flask looks in the templates folder to find the html file.

Run the program and view the file in your browser. It should look like this:

Adding CSS

The page so far looks pretty boring, like a web page from 1995. We can improve things a little bit by adding come colour and using different fonts. We do this using a CSS (cascading style sheets) file, like this:

body {
  background: Linen;
  margin-top: 50px;
  margin-left: 100px;
  }

p {
  font-family: Georgia, serif;
  font-size: 1.2em;
  color: DarkSlateGray;
  }

h1 {
  font-family: Verdana, Geneva, sans-serif;
  font-size: 2.5em;
  color: FireBrick;
  }

This code adds a background colour, and sets margins so that the text isn’t crammed into the top corner. It also sets the font, size and colour of the heading text (h1) and the paragraph text (p). You can change these values if you wish.

Create a folder called static, under your working folder. Name the file main.css and store it in the folder.

You will also need to edit your html file to include the CSS file. Add the extra line in the head section like this:

<html>
  <head>
    <link rel="stylesheet" href='/static/main.css' />
  </head>
  <body>
    <h1>Home page</h1>
    <p>My first Flask site</p>
  </body>
</html>

Your page should now look like this:

adding-html-2