HTML and CSS

Five lessons about what any page is made of: tags, links, forms and styling. In the last lesson Python builds the HTML itself. Click “Show” to see the result right away.

It is best to start after the “Python from scratch” lessons: the last lesson uses functions and loops. Unfamiliar words are in the glossary.

0 of 5 lessons done

The composing room of a newspaper in Medan: rows of type cases, 1898
  1. Lesson 1. What HTML is: tags and the page skeleton

    Why. When you open a site, a Python server answers the browser with text in the HTML language. The browser reads this text and draws the page. To make your own site, you need to know how this text is built.

    What HTML is. It is a markup language, not a program. It has no conditions or loops. HTML simply labels parts of the text: “this is a heading”, “this is a paragraph”, “this is an important word”.

    Tags. A label is called a tag and is written in angle brackets. Tags usually come in pairs: an opening <p> and a closing </p> with a slash. The text between them is the content. A tag together with its content is called an element.

    The most useful tags:

    • <h1>…<h6> — headings, <h1> is the main one and usually there is one per page;
    • <p> — a paragraph of text;
    • <strong> — important words, the browser shows them in bold, <em> — emphasis in italics;
    • <br> — a line break. It is a single tag, you don't need to close it.

    Nesting. Tags are put inside each other like boxes: <p>This is <strong>important</strong></p>. They are closed in reverse order: first the inner one, then the outer one.

    The page skeleton. Every page has the same frame: the line <!doctype html>, then <html>, inside it <head> with technical information, for example the tab title <title>, and <body> — everything you see on the page.

    Try it: click “Show” under the examples. Change the heading text, add one more paragraph and click “Show” again.

    Common mistake: a tag left open

    If you don't close <strong>, the browser will make all the text bold until the end of the page. It won't show an error, the page will just look strange. Check that every paired tag has a closing tag with a slash.

    Common mistake: closing in the wrong order

    <p><strong>text</p></strong> is wrong: the boxes “cross”. Close them from the inner one to the outer one: <p><strong>text</strong></p>.

    In short:

    • HTML labels parts of the text with tags: <h1>, <p>, <strong>;
    • a paired tag is closed with a slash, nested tags are closed in reverse order;
    • the page skeleton: <html>, inside it <head> for technical things and <body> for what is visible.
    Example 1. First tags
    <h1>Hi, I'm Aruzhan</h1>
    <p>I'm learning to make websites with <strong>Python</strong>.</p>
    <p>This is my second paragraph.<br>And this is a new line in it.</p>
    <h2>My plans</h2>
    <p>To make <em>my own</em> first website.</p>
    Example 2. A full page skeleton
    <!doctype html>
    <html lang="en">
    <head>
      <meta charset="utf-8">
      <title>My business card</title>
    </head>
    <body>
      <h1>Yerlan Nurlanov</h1>
      <p>Learning to program in Astana.</p>
    </body>
    </html>

    Exercise: your first page

    Level: Easy

    Write the markup: a main heading My first site and two paragraphs with any text below it.

    Show the solution
    <h1>My first site</h1>
    <p>Here I tell about myself.</p>
    <p>And here about my plans.</p>

    A harder exercise: a business card skeleton

    Level: Medium

    Build a full page skeleton: html, inside it head with the tab title Business card and body with a main heading — your name.

    Show the solution
    <!doctype html>
    <html lang="en">
    <head>
      <meta charset="utf-8">
      <title>Business card</title>
    </head>
    <body>
      <h1>Dana Smagulova</h1>
    </body>
    </html>
  2. Lesson 2. Lists, links and images

    Why. A site menu is a list of links. A product card is an image with a caption. These three tags appear on almost every page.

    Lists. <ul> is a bulleted list, <ol> is a numbered one. Each item goes in <li>. It is like a list in Python, only for showing on a page.

    Links. <a href="address">text</a>. The href attribute holds where the link leads, and between the tags goes the text you click.

    Attributes are extra information inside the opening tag: name="value". A link has href, an image has src and alt.

    Full and short addresses. https://www.python.org leads to another site. about.html leads to a page of this same site, the path is counted from the current page.

    Images. <img src="address" alt="description"> is a single tag. src is where to get the image. alt is the text instead of the image: screen readers for blind people read it, and it is shown if the image didn't load. Write in it what the image shows.

    Try it: add your own item with a link to the menu. In the image example change width to 150.

    Common mistake: an address without https://

    The browser will read <a href="www.python.org"> as a page of this same site called “www.python.org” and open a 404 error. Write the address of another site in full: https://www.python.org.

    Common mistake: an image without alt

    Without alt a blind user will only hear “image” or the file name. Describe the point: not “picture1” but “A python on an old engraving”. If the image is pure decoration, write an empty alt="".

    In short:

    • <ul> and <ol> are lists, items go in <li>;
    • <a href="..."> is a link, the address of another site is written with https://;
    • <img src="..." alt="..."> is an image, and alt is required.
    Example 1. A menu of links
    <h2>Menu</h2>
    <ul>
      <li><a href="https://pywebguide.github.io/en/">Home</a></li>
      <li><a href="https://pywebguide.github.io/en/start.html">Python from scratch</a></li>
      <li><a href="https://www.python.org">Python website</a></li>
    </ul>
    <h2>Plan for the week</h2>
    <ol>
      <li>Go through the HTML lessons</li>
      <li>Make a business card</li>
    </ol>
    Example 2. An image with a caption
    <img src="https://pywebguide.github.io/assets/img/snakes.webp"
         alt="An old engraving: eight snakes, among them a reticulated python"
         width="300">
    <p>Python is named not after the snake but after a comedy show.</p>

    Exercise: favourite fruit

    Level: Easy

    Make a bulleted list of three favourite fruits.

    Show the solution
    <ul>
      <li>apple</li>
      <li>pear</li>
      <li>aport apple</li>
    </ul>

    A harder exercise: a link and an image

    Level: Medium

    Make a link with the text Python website that leads to https://www.python.org. Below it put an image with the address https://pywebguide.github.io/assets/img/snakes.webp and a clear description in alt.

    Show the solution
    <a href="https://www.python.org">Python website</a>
    <img src="https://pywebguide.github.io/assets/img/snakes.webp" alt="An engraving with snakes">
  3. Lesson 3. Forms: how a site receives data

    Why. Sign-up, search, a review, an order — all of these are forms. It is through a form that data from a person reaches the server, your Python program.

    The <form> tag groups fields together. The action attribute says where to send the data, and method says how.

    Fields. <input> is a single tag for input. Its kind is set by type: text — text, email — email, password — a password shown as dots, number — a number, checkbox — a tick box. For long text there is <textarea>, for sending — <button>.

    The name attribute matters most. It is the name under which the value reaches the server. In Flask it becomes a dictionary key: request.form["email"]. Without name the field isn't sent at all.

    The <label> caption. Connect the caption to the field: the field has id="email", the caption has for="email". Then clicking the caption puts the cursor in the field, and screen readers read the caption aloud.

    GET and POST. method="get" puts the data into the page address, this is how search works: ?q=python. method="post" sends it hidden, in the request body: this is how passwords and reviews are sent.

    Try it: add an age field with type="number" to the form. Sending is turned off in the preview window, but the fields work: you can type in them.

    Common mistake: a field without name

    If you forget name, the browser will show the field and even let you type in it, but the value won't reach the server. In Python request.form["email"] will fail with KeyError. Check that every field has a name.

    Common mistake: a password sent with GET

    With method="get" the password ends up right in the address bar and in the browser history. For forms with passwords and personal data always use method="post".

    In short:

    • <form> groups fields, method="post" is for personal data, get is for search;
    • <input type="..." name="...">: the value reaches the server by its name;
    • <label for="id"> connects a caption to a field.
    Example 1. Sign-up
    <form action="/register" method="post">
      <p>
        <label for="name">Name</label><br>
        <input id="name" name="name" type="text" placeholder="Aruzhan" required>
      </p>
      <p>
        <label for="email">Email</label><br>
        <input id="email" name="email" type="email">
      </p>
      <p>
        <label for="password">Password</label><br>
        <input id="password" name="password" type="password">
      </p>
      <button type="submit">Sign up</button>
    </form>
    Example 2. What the server receives
    # This is how form data looks on the server (Flask: request.form)
    form = {"name": "Aruzhan", "email": "aru@example.com", "password": "secret"}
    
    print("New user:", form["name"])
    print("Email:", form["email"])
    print("Has a password?", "password" in form)

    Exercise: newsletter subscription

    Level: Easy

    Make a subscription form: one email field with type="email" and name="email" and a submit button.

    Show the solution
    <form action="/subscribe" method="post">
      <input type="email" name="email" placeholder="Your email">
      <button type="submit">Subscribe</button>
    </form>

    A harder exercise: a login form

    Level: Medium

    Make a login form with method="post": a username field (name="username") with a caption connected through for and id, a password field (name="password", type="password") and a button.

    Show the solution
    <form action="/login" method="post">
      <label for="username">Username</label>
      <input id="username" name="username" type="text">
      <input name="password" type="password">
      <button type="submit">Log in</button>
    </form>
  4. Lesson 4. CSS: how a page looks

    Why. HTML says what is on the page: a heading, a paragraph, a button. And CSS says how it looks: colours, sizes, spacing. This very site is styled with CSS.

    Where to write it. The easiest is in the <style> tag at the top of the page. Big sites move CSS into a separate file.

    A CSS rule consists of a selector and properties in curly braces: h1 { color: navy; }. It reads: “all h1 are dark blue”. A semicolon goes after each property.

    Selectors:

    • by tag: p { ... } — all paragraphs;
    • by class: .card { ... } — all elements with class="card". This is the most common way;
    • by id: #top { ... } — one element with id="top".

    Useful properties. color — text colour, background — background, font-size — font size, font-weight: bold — boldness, text-align: center — alignment. padding — spacing inside the border, margin — outside, border — a border, border-radius — rounded corners.

    Colours are set with a word (red) or a code: #ffd249 is this site's yellow.

    Try it: change the card background to #a4f6f8 and the rounding to 20px.

    Common mistake: a dot in the class attribute

    The dot is written only in CSS: .card { ... }. In HTML the class is given without it: class="card". With a dot, class=".card", the rule won't work.

    Common mistake: a missing semicolon

    In color: red background: yellow; there is no semicolon after red, and the browser skips both properties. It won't show an error: the style just won't apply. Put ; after every property.

    In short:

    • HTML is what is on the page, CSS is how it looks;
    • a rule: selector { property: value; }, a class in CSS is written with a dot;
    • padding is spacing inside, margin is spacing outside.
    Example 1. Styling text
    <style>
      h1 { color: #2f6694; font-size: 40px; }
      p { font-size: 18px; color: #333333; }
      .important { background: #ffd249; font-weight: bold; }
    </style>
    
    <h1>The PyWeb Guide course</h1>
    <p>An ordinary paragraph.</p>
    <p class="important">And this paragraph is highlighted with a class.</p>
    Example 2. A product card
    <style>
      .card {
        width: 220px;
        padding: 16px;
        margin: 12px;
        background: #ffc4ef;
        border: 2px solid #0d0d0d;
        border-radius: 12px;
      }
      .price { font-size: 24px; font-weight: bold; }
    </style>
    
    <div class="card">
      <h2>Notebook</h2>
      <p class="price">450 tenge</p>
    </div>

    Exercise: a blue heading

    Level: Easy

    Add a CSS rule so that the h1 heading becomes the colour #2f6694.

    Show the solution
    <style>
      h1 { color: #2f6694; }
    </style>
    <h1>My site</h1>

    A harder exercise: your own card

    Level: Medium

    Make a <div class="card"> block with a heading inside and a .card rule that has a background (background), inner spacing (padding) and rounded corners (border-radius).

    Show the solution
    <style>
      .card { background: #ffc4ef; padding: 16px; border-radius: 12px; }
    </style>
    <div class="card">
      <h2>Notebook</h2>
    </div>
  5. Lesson 5. How Python builds HTML

    Why. On a real site HTML isn't written by hand for every user. It is built by a program on the server: it fills in a name, a task list, prices. This lesson connects everything you know about Python and HTML.

    HTML is just a string. For Python a page is ordinary text. So it can be built with an f-string: f"<h1>Hello, {name}!</h1>".

    Lists become a loop. To show a task list, the program goes through it and adds an <li> line for each task. This is how feeds, catalogues and menus are made.

    Danger: someone else's code in the page. If you insert a user's text into HTML as is, they can write their own tag there, for example <script>, and this code will run for other visitors. This attack is called XSS. The protection is the html.escape function: it turns < into the safe &lt;, and the browser shows the character instead of running the tag.

    Templates. Gluing big pages together from strings is awkward. So Flask and Django use templates: an HTML file with gaps {{ name }} and loops {% for %}. They call escape for every value themselves. More on the “Templates and forms” page.

    Try it: in the first example add a task to the list. In the second change the comment text and compare the output with and without escape.

    Common mistake: inserting user text without escape

    The comment <script>alert(1)</script>, inserted as is, becomes part of the page. Pass any text that came from a user through html.escape(), or use templates that do it themselves.

    Common mistake: forgetting to close the tag after the loop

    If you add <li> in a loop but forget </ul> after the loop, the list “stretches” over the whole page. The opening tag goes before the loop, the closing one after it.

    In short:

    • for Python HTML is an ordinary string: it is built with f-strings and loops;
    • always pass user text through html.escape;
    • in Flask and Django templates do it, and that is the next step.
    Example 1. A page from a list
    name = "Aruzhan"
    tasks = ["learn tags", "make a form", "style with CSS"]
    
    page = f"<h1>Tasks: {name}</h1>\n<ul>\n"
    for task in tasks:
        page += f"  <li>{task}</li>\n"
    page += "</ul>"
    
    print(page)
    Example 2. Protection with escape
    import html
    
    comment = "<script>alert('hacked')</script>"
    
    print("Dangerous:", f"<p>{comment}</p>")
    print("Safe:     ", f"<p>{html.escape(comment)}</p>")

    Exercise: a product card from Python

    Level: Easy

    Write a function card(name, price). It returns the card HTML: <div class="card"><h2>Notebook</h2><p>450 tenge</p></div> for card("Notebook", 450).

    Show the solution
    def card(name, price):
        return f'<div class="card"><h2>{name}</h2><p>{price} tenge</p></div>'

    A harder exercise: a safe list

    Level: Medium

    Write a function render_list(items) that returns an HTML list: <ul><li>bread</li><li>milk</li></ul>. Pass each item through html.escape, because the items may have been written by a user.

    Show the solution
    import html
    
    
    def render_list(items):
        result = "<ul>"
        for item in items:
            result += f"<li>{html.escape(item)}</li>"
        return result + "</ul>"

What's next

Now you know what a page is made of. All that's left is to set up your computer and build your first site on Flask or Django.