COSC203 Web, Databases, and Networks
Toggle Dark/Light/Auto modeToggle Dark/Light/Auto modeToggle Dark/Light/Auto modeBack to homepage

Lab 1: HTML Basics

๐ŸŽฏ Lab Objective

In this lab, you will learn the fundamental concepts of HTML documents.

This lab teaches the following concepts:

  1. HTML Elements
  2. HTML Tags
  3. Nesting Elements
  4. Element Attributes
  5. Hyperlinks

Table of Contents

1. The Lab Computers

The labs are held in Owheo, G.37 or G38 (Lab E or Lab F). The lab exercises are designed to be viewed on Google Chrome. You may instead use your own computer, but you will have to install some development tools.

If you haven’t logged into lab compters before, your login is the same as your your university login. If you cannot log in, ask a demonstrator for help (or anyone else nearby).


2. Visual Studio Code

Visual Studio Code (VSC) is a flexible IDE designed for modern software development. Conventiently it is already installed on the lab computers.

โœ… Tip

If using the lab computers, use the shortcode to VS Code under Coursework K:\ VS Code Shortcut

This shortcut tells VS Code to use J:\ Drive for settings/extensions. This way your settings will load on any lab computer.

  • C:\ local storage
  • H:\ home drive (small and slow)
  • J:\ Warpdrive (fast and large)
  • K:\ Coursework (readonly files)

To assist our web development we will install the “Live Server” extension, which will allow us to preview our HTML documents as we write them.

๐Ÿ“ Task 1: Get Visual Studio Code running
  1. If working from your own computer
  2. Open Visual Studio Code
  3. Install the “Live Server” Extension
    1. Open Extension Marketplace
    2. Search “Live Server”
    3. Click Install

VS Code extension Live Preview

โœ… Keyboard Shortcuts

Knowing all the features (and keyboard shortcuts) is crucial to being a productive developer.

Visual Studio Code keyboard shortcuts:


3. HTML

HTML is not a programming language, it is a declarative language. Programming languages like Python or Java tell the computer how to do things. Declarative languages like HTML tell the computer what it should do. That’s not a great explanation, but it will become clear soon.

Programming languages have control flow. The code defines an order of instructions to be executed. The order of these instructions can be changed with conditionals (like if) and loops (like while). In HTML there is no control flow.

We still write HTML in plain text saved to files; with the .html extension. Web browsers read .html files and render the document. Let’s take a look a simple example. Below is “hello world” in HTML.

hello_world.html

HTML
CSS
JavaScript
Result

We will explain what everything means shortly.

๐Ÿ“ Task 2: Hello World in HTML
  1. Create a new folder for this lab
    • name it something useful, like “Lab01”
  2. From Visual Studio Code open this folder
    • File > Open Folder
  3. Create a new file in this folder
    • Ctrl+n or โŒ˜+n
    • save the file as hello_world.html
  4. Type the hello world example above (and save)
  5. Start the Live Server

There are a few ways to start Live Server:

  • A: Right Click “helloworld.html” > Open with Live Server
  • B: Click “Go Live” in bottom right

VS Code extension Live Preview

  • C: search for “live server” in the Command Palette. Open the Command Palette with the keyboard shortcut โŒ˜+P (macOS) or Ctrl+Shift+P (Win/Linux).

If Live Server doesn’t open a web browser, do so yourself and visit: 127.0.0.1:5500/hello_world.html You should see that our smiley emoji rendered all glitchy, or “Zฬทอ‘ฬ—Aฬธฬƒฬ™LฬตฬฬžGฬดฬฟฬฉOฬดฬ‹ฬณ”. We will fix this shortly.

Preview HTML window

โœ… Web Servers

Web servers are programs that “serve” HTML files (and other files). You don’t always need a web server to view an HTML document, but it will make things easier as our projects grow.

Thankfully, the Live Server extension handles everything for us.


4. Debugging HTML

There are many ways to find bugs in HTML documents. The W3C Validator is probably the best tool to find errors in .html files, like our hello world example.

๐Ÿ“ Task 3: Validate helloworld.html
  1. Upload your .html file to the W3C Validator
  2. Read through all the errors and warnings before continuing.
โœ… W3C
The W3C (World Wide Web Consortium) is a community dedicated to developing international standards for the World Wide Web. The consortium was founded, and is currently led by the inventor of the World Wide Web, Tim Berners-Lee. Essentially, the W3C recommendations are gold standard.

HTML errors

The validator should report 3 errors and 1 warning, and yet, a a modern browser like Chrome can render the document mostly okay. Modern browsers are very tolerant of malformed and invalid HTML because the internet is the wild west of spaghetti code.

In these course we expect you to write valid HTML, outside you may write however you like.

W3C Error Log

We will fix (and explain) the 4 issues in this order:

  1. Missing the “DOCTYPE” declaration (#3)
  2. Missing the Element “head” (#4)
  3. Missing the “lang” attribute (#1)
  4. Missing the character encoding declaration (#2)

5. DOCTYPE Declaration

The missing DOCTYPE declaration is the easiest issues to resolve.

The first line of a plain text file often describes how the rest of the file should be interpreted. For example, the first line of a Python script is usually a shebang. Something like this:

#!/usr/bin/env/ python3

print("hello World! ๐Ÿ")

The shebang is not executable Python code, its metadata which informs anyone/anything reading the file that it is a Python script, specifically Python 3. In HTML, the first line should always, always, be the DOCTYPE declaration, and it looks like this:

<!DOCTYPE html>
<html>
    <body>
        <h1>Hello World! ๐Ÿ˜ƒ</h1>
    </body>
</html>
๐Ÿ“ Task 4: Declare the DOCTYPE
Add the HTML DOCTYPE declaration to your helloworld.html file.
โœ… HTML versions

The following DOCTYPE declaration is HTML5

<!DOCTYPE html>

HTML5 became an official W3C recommendation in late 2014. However, if for some reason you need to develop a website in HTML4, then you would use a more complicated DOCTYPE declaration:

<!DOCTYPEย HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

These labs are designed for HTML5.


6. HTML Elements and Tags

HTML documents are made out of elements. HTML elements are defined with opening and closing tags. Tags are keywords enclosed within “angle brackets” <>.

For a paragraph of text we use a paragraph element, which begins with the opening tag <p> and ends with the closing tag </p> (note the / in the closing tag).

Tags and Element

If we refer back to our hello world example again we can see 3 elements, defined by 6 tags (html, body, and h1). These three elements overlap each other, in a way we call nested, like the Russian Matryoshka Doll ๐Ÿช†๐Ÿช†๐Ÿช†

<!DOCTYPE html>
<html>
    <body>
        <h1>Hello World! ๐Ÿ˜ƒ</h1>
    </body>
</html>

These three elements are:

  • <html> ... </html> defines the root HTML document.
  • <body> ... </body> defines the body of the HTML document.
  • <h1> ... </h1> defines a heading. Also known as “heading level 1”.

The following diagram shows our 3 nested elements as a Box Model. Where h1 is inside body, and body is inside html.

flowchart TD
    subgraph html
        subgraph body
            direction LR
            subgraph h1
                text2["Hello World! ๐Ÿ˜ƒ"]
            end
        end
    end
style html fill:#ff03,stroke-width:2px,stroke:#333
style body fill:#4186c988,stroke-width:2px,stroke:#333
style h1 fill:#4186c988,stroke-width:2px,stroke:#333
style text2 stroke:#333,stroke-width:1px

โœ… Indentation

In HTML, Indentation is optional. Using whitespace can help show the nested structure, but it doesn’t change how the document will be rendered.

For example, this:

<!DOCTYPE html><html><body><h1>Hello World! ๐Ÿ˜ƒ</h1></body></html>

and this:

<!DOCTYPE html>
<html>
<body>
<h1>Hello World! ๐Ÿ˜ƒ</h1>
</body>
</html>

… are both the same as our first hello world.

Head Element

Let’s fix the missing head element issues. And also give our document a title at the same time.

Along with the DOCTYPE declaration, there are 3 more things every HTML file requires:

  1. html is the root of the HTML document
    • everything must be contained within the root
  2. head is the the document’s metadata
    • extra information like: title, author, style, encoding, scripts, …
  3. body is the required element for the document content
    • the actual content of the document (paragrahs, images, etc…)
flowchart
	subgraph html
		direction LR
		subgraph head
			text1["document meta data here"]
		end
		subgraph body
			text2["document content here"]
		end
	end
style html fill:#ff03,stroke-width:2px,stroke:#333
style body fill:#4186c988,stroke-width:2px,stroke:#333
style head fill:#4186c988,stroke-width:2px,stroke:#333
style text1 fill:#0000,stroke:#3338,stroke-width:2px,stroke-dasharray:10
style text2 fill:#0000,stroke:#3338,stroke-width:2px,stroke-dasharray:10
๐Ÿ“ Task 5: Declare the HTML elements head and title
  1. Insert a <head></head> element to your .html file.
    • head belongs inside html but outside body.
    • head comes before body.
  2. Insert a <title></title> element inside head
  3. Give your document a title
    • by inserting text within the title element.

The Box Model of our document should now look something like this:

flowchart TD
	subgraph html
        direction LR
        subgraph head
            subgraph title
                text1["my custom title :-)"]
            end
        end
        subgraph body
            direction LR
            subgraph h1
                text2["Hellow World! ๐Ÿ˜ƒ"]
            end
        end
    end
style html fill:#ff03,stroke-width:2px,stroke:#333
style head fill:#4186c988,stroke-width:2px,stroke:#333
style title fill:#4186c988,stroke-width:2px,stroke:#333
style body fill:#4186c988,stroke-width:2px,stroke:#333
style h1 fill:#4186c988,stroke-width:2px,stroke:#333
style text1 stroke:#333,stroke-width:1px
style text2 stroke:#333,stroke-width:1px

A web browser should now render your custom title in the window tab.

Custom title in firefox

Let’s fix the emoji next!


7. Element Attributes

HTML attributes add extra information for elements. Attributes always appear in the opening tag (never in the closing tag). Attributes are defined in name="value" pairs.

The Language Attribute

It is good practice to use the lang attribute to declare the language your web page is writtin in.

Declaring the language (e.g. English / Te Reo) can help the web browser to render the document. e.g. some languages render text from right-to-left. Declaring the language is also basic Search Engine Optimization (SEO). If a Search Engine knows the language a document is written in, it will show the document only to people who speak that language.

English

<html lang="en">

New Zealand English

<html lang="en-nz">

Mฤori

<html lang="mi">
โœ… Multi-Lingual HTML Documents

If an HTML document needs to contain several languages, you may set the lang attribute on specific elements.

<body>
    <h1 lang="en">hello everyone ๐Ÿ‘‹</h1>
    <h1 lang="mi">Kia ora tฤtou ๐Ÿ‘‹</h1>
    <h1 lang="sm">Talofa tagata uma ๐Ÿ‘‹</h1>
    <h1 lang="zh-cn">ๅคงๅฎถๅฅฝ ๐Ÿ‘‹</h1>
</body>
๐Ÿ“ Task 6: Declare the lang attribute

Declare the language of your HTML document.

  1. Give your <html> tag a lang attribute
  2. Set the attribute to "en", "en-nz", or "mi"

Character Encoding Attribute

Unicode is an international standard for text and emoji characters. UTF-8 encoding is the most popular implementation of Unicode because it is backwards compatible with older encoding implementations like ASCII. If we declare UTF-8 our emoji will magically work.

โœ… Unicode and UTF-8
If you would like to learn more about UTF-8 watch Tom Scott talking about UTF-8 here.
๐Ÿ“ Task 7: Declare the charset encoding

Declare your document’s character set as UTF-8 encoding.

  1. Insert a <meta> tag inside your head element.
  2. Give your <meta> element a charset attribute.
  3. Set the charset attribute to "UTF-8".
<head>
	<meta charset="UTF-8">
</head>
โœ… Tip
The <meta> element is special as it requires only 1 tag, a self-closing tag. We call these Empty Elements. Another Empty Element is <img> for the Image Element.

The Box Model of your document should now look something like this:

flowchart TD
    subgraph html
        l(["lang=“en”"])
        direction LR
        subgraph head
            direction LR
            subgraph title
                direction TB
                text1["my custom title :-)"]
            end
			subgraph meta
                c(["charset=“UTF-8”"])
            end
        end
        subgraph body
            direction LR
            subgraph h1
                text2["Hellow World! ๐Ÿ˜ƒ"]
            end
        end
    end
    style c fill:#f79,stroke:#333,stroke-width:2px
    style l fill:#f79,stroke:#333,stroke-width:2px
    style html fill:#ff03,stroke-width:2px,stroke:#333
    style head fill:#4186c988,stroke-width:2px,stroke:#333
    style meta fill:#4186c988,stroke-width:2px,stroke:#333
    style title fill:#4186c988,stroke-width:2px,stroke:#333
    style body fill:#4186c988,stroke-width:2px,stroke:#333
    style h1 fill:#4186c988,stroke-width:2px,stroke:#333
    style text1 stroke:#333,stroke-width:1px
    style text2 stroke:#333,stroke-width:1px

8. Semantic Elements

Semantic Elements provide structure to HTML documents. Building web pages with them helps with both accessibility browsers (e.g. screen readers for the sight impaired), and also SEO. If a search engine can better understand the structure of your web page, it can extract better information.

Let’s build a bigger web page with several of these semantic elements.

๐Ÿ“ Task 8: Create index.html

Use what you have learned so far to create an HTML5 file using Blueprint below.

  1. Create a new file called index.html
  2. Insert
    • HTML doctype
    • tags for the html element
    • tags for the head and body elements (inside html)
  3. Insert the following semantic elements (inside body)
    • header
    • nav
    • main
    • footer
  4. Insert the rest of the tags/attributes/text from the Blueprint below.
    • The <img> element needs the file: polly.jpg saved into the same directory as index.html
  5. Upload index.html to the W3C Validator
    • ensure it reports 0 errors and 0 warnings

The Blueprint for index.html

Each element in this blueprint is explained in the table beneath.

flowchart TD
    subgraph html
        l(["lang=“en”"])
        direction LR
        subgraph head
            subgraph meta
                c(["charset=“UTF-8”"])
            end
            subgraph title
                direction TB
                text1["Polly's Travel Blog"]
            end
        end
        subgraph body
            direction LR
             subgraph header
                subgraph h1
                    text2["Polly's Travel Blog"]
                end
            end
            subgraph nav
                direction LR
                subgraph navTitle["h2"]
                    Navigation
                end
                subgraph ul
                    subgraph navList1["li"]
                        subgraph navLink1["a"]
                            direction LR
                            href1(["href=“index.html”"])
                            navName1["Home"]
                        end
                    end
                    subgraph navList2["li"]
                        subgraph navLink2["a"]
                            href2(["href=“stories.html”"])
                            navName2["Stories"]
                        end
                    end
                    subgraph navList3["li"]
                        subgraph navLink3["a"]
                            href3(["href=“contact.html”"])
                            navName3["Contact"]
                        end
                    end
                end
            end
			subgraph main
				subgraph section
					direction LR
					subgraph sectionHeader["h2"]
						text4["Polly the Penguin ๐Ÿง"]
					end
					subgraph img
                        direction LR
						src(["src=“polly.jpg”"])
                        alt(["alt=“Photo of Polly”"])
					end
					subgraph sectionP["p"]
						text5["Stories about my life as a penguin!"]
					end
				end
				subgraph section2["section"]
					subgraph articleHeader["h2"]
						text6["Leaving Home"]
					end
					subgraph articleP["p"]
						text7["Today I travel for Antarctica!"]
					end
                    subgraph articleP2["p"]
						text8["I will bring my favourite scarf."]
					end
				end
			end
            subgraph footer
                subgraph footerLink["p"]
                        text3["ยฉ Copyright 2022 by Polly. No rights reversed."]
                end
            end
        end
    end
    style l fill:#f79,stroke:#333,stroke-width:2px
    style c fill:#f79,stroke:#333,stroke-width:2px
    style href1 fill:#f79,stroke:#333,stroke-width:2px
    style href2 fill:#f79,stroke:#333,stroke-width:2px
    style href3 fill:#f79,stroke:#333,stroke-width:2px
    style src fill:#f79,stroke:#333,stroke-width:2px
    style alt fill:#f79,stroke:#333,stroke-width:2px
    style html  fill:#ff03,stroke-width:2px,stroke:#333
    style head  fill:#4186c955,stroke-width:2px,stroke:#333
    style meta  fill:#4186c955,stroke-width:2px,stroke:#333
    style title fill:#4186c955,stroke-width:2px,stroke:#333
    style body fill:#4186c955,stroke-width:2px,stroke:#333
    style header fill:#4186c955,stroke-width:2px,stroke:#333
    style h1 fill:#4186c955,stroke-width:2px,stroke:#333
    style nav fill:#4186c955,stroke-width:2px,stroke:#333
    style navTitle fill:#4186c955,stroke-width:2px,stroke:#333
    style ul fill:#4186c955,stroke-width:2px,stroke:#333
    style navList1 fill:#4186c955,stroke-width:2px,stroke:#333
    style navLink1 fill:#4186c955,stroke-width:2px,stroke:#333
    style navList2 fill:#4186c955,stroke-width:2px,stroke:#333
    style navLink2 fill:#4186c955,stroke-width:2px,stroke:#333
    style navList3 fill:#4186c955,stroke-width:2px,stroke:#333
    style navLink3 fill:#4186c955,stroke-width:2px,stroke:#333
    style sectionHeader fill:#4186c955,stroke-width:2px,stroke:#333
    style img fill:#4186c955,stroke-width:2px,stroke:#333
    style sectionP fill:#4186c955,stroke-width:2px,stroke:#333
    style articleP2 fill:#4186c955,stroke-width:2px,stroke:#333
    style articleHeader fill:#4186c955,stroke-width:2px,stroke:#333
    style articleP fill:#4186c955,stroke-width:2px,stroke:#333
    style footerLink fill:#4186c955,stroke-width:2px,stroke:#333
    style section fill:#4186c955,stroke-width:2px,stroke:#333
	style main fill:#4186c955,stroke-width:2px,stroke:#333
    style section2 fill:#4186c955,stroke-width:2px,stroke:#333
    style footer fill:#4186c955,stroke-width:2px,stroke:#333
    style text1 stroke:#333,stroke-width:1px
    style text2 stroke:#333,stroke-width:1px
    style text3 stroke:#333,stroke-width:1px
    style text4 stroke:#333,stroke-width:1px
    style text5 stroke:#333,stroke-width:1px
    style text6 stroke:#333,stroke-width:1px
    style text7 stroke:#333,stroke-width:1px
    style text8 stroke:#333,stroke-width:1px

HTML Element Reference

The below tables lists the elements we have seen so far.

For a full reference of HTML elements, check the Mozilla web docs.

Tag(s)PurposeParent ElementSelf-closing
<html>...</html>Root element of every HTML pageno
<head>...</head>Metadata for web browsers and SEO<html>no
<body>...</body>Content of the document<html>no
<meta>Extra information<head>yes
<title>...</title>Document title<head>no
<header>...</header>Semantic Element for the page header<body>no
<footer>...</footer>Semantic Element for the page footer<body>no
<main>...</main>Semantic Element for the main content<body>no
<nav>...</nav>Semantic Element for the site navigationno
<section>...</section>Semantic Element for a section<main>no
<a>...</a>A “link”, or anchor to a url (hyper-link)no
<p>...</p>Paragraph of textno
<h1>...</h1>Header level 1no
<h2>...</h2>Header level 2no
<ul>...</ul>Bullet list (Unordered)no
<li>...</li>List item<ul>no
<img>Image embedyes
โœ… Image Element

The Image Element has a few special characteristics.

<img src="url/filename.jpg" alt="Description of the image">
  • The img element uses a self-closing tag (like the meta element)
  • The src attribute is a url, which points to the image source.
    • The url could point to anywhere on the internet (hot linking)
    • Or, it could point to a local file, with an absolute or relative path.
  • The alt attribute is an alternative description of the image.
    • for SEO and accessibility browsers (e.g. screen readers).

Web links or hyperlinks are an important concept for the web. They allow us to link HTML pages together to create an interconnected web of pages.

Web of Documents

In HTML, hyperlinks are created with Anchor Elements with the <a> tag. Clicking on an anchor element will load that HTML page.

Below are two examples of hyperlinks, the first has a relative URL that links a local HTML document, the second has an absolute URL that links to another website.

<a href="contact.html">Click Me!</a>
<a href="https://google.com">Google</a>

An anchor tag does nothing without the href attribute (hyperlink reference). The value of the href attribute is the destination we want our link to go, which is either a relative URL or an absolute URL.

๐Ÿ“ Task 9: Create a multi-page site

In this task we will create a multi-page site.

  1. Start with index.html from the previous task(s).
  2. Create 2 copies in the same directory
    • stories.html
    • contact.html
  3. Change the h1 element(s) of each page to something more descriptive
    • html > body > header > h1
  4. Change the main content of the 2 new pages to something else
    • html > body > main
  5. For anchor elements that link to their own page, change the href to "#!"
  6. Test your sites page navigation by clicking the hyperlinks in the <nav> element
โœ… Tip

The hash value "#" in a href indicates a URL fragment and is used to link directly to a specific element within a page.

For example, the below link uses the URL fragment #Examples so clicking the link will open the page and scroll down to the Example section on the page.

https://en.wikipedia.org/wiki/URI_fragment#Examples

<a href=https://en.wikipedia.org/wiki/URI_fragment#Examples>https://en.wikipedia.org/wiki/URI_fragment#Examples<a>

Using the href value #! is standard practice to link nowhere.

Linking to other resources (non-HTML)

Along with HTML documents, anchor tags can link to various different resource files on the internet. The href URL may refer to: images, videos, audio, zip files etc. Modern web browsers will open many file types (images, video, pdf, etc.) but if the resource file is not supported, clicking the link will simply download file, the default behaviour.

Link other resources

<a href="polly.jpg">an image</a>
<a href="data.zip">a download</a>

Protocol and Scheme

Absolute URLs begin with the protocol e.g https: in https://www.google.com/. The protocol tells the web browser how to retrieve the page. The 3 most common are https:, http:, and ftp:.

There are also Resource Scehemes which are very similar, the two we will look at are mailto: and tel: Which identify an email address and a phone number respectively.

Link email and phone

<a href="mailto:name@mail.nz" >email</a>
<a href="tel:+64034798397" >phone</a>

Preview

email
phone

Clicking the above links on a smart phone should open an email app or phone app.

๐Ÿ“ Task 10: Create some contact links
  1. Create 3 anchor elements in the contact.html page
    • Somewhere in html > body > main > section
  2. Make one link to another website with https:
  3. Make one link to an email address with mailto:
  4. Make one link to a telephone number with tel:
โœ… Tip

The anchor element may also have a target attribute, which specifies where to open the link. In the current window or in a new window/tab.

<a target="_self" href="https://google.com/" >open in this window</a>

<a target="_blank" href="https://google.com/" >open in a new window or tab</a>

11. Emmet

Last section! ๐ŸŽ‰

Writing HTML can be tiresome which is why Emmet was created. Emmet is like auto complete for HTML, and Visual Studio Code has Emmet built in.

Let’s start off by generating some HTML boilerplate with Emmet. If you open a blank file in VS Code (with a .html extension) and type !, it will trigger an Emmet Abbreviation.

Emmet Abbreviation

Pressing enter will generate the following HTML boilerplate:

Emmet Expansion

That is just 1 of many Emmet abreviations. There are 3 other abbrevations you may find useful:

  • > creates a child element
  • + creates a sibling element
  • * creates multiple elements

You can chain these abbrevations together in order to create a complex structure of HTML elements. To understand what that all means you could read the Emmet documentation, or watch the demonstration video below which finishes the previous lab excercise in less than a minute!

Below are the Emmet abbreviations used in the above demo.

  • !!!
  • html>head+body
  • header>h1
  • nav>ul>li*3>a
  • main>section>h2+img+p
  • section>h2+p*3
  • footer>p
  • meta[charset=UTF-8]
โœ… Emmet Cheat Sheet

If you want to become a Emmet power user read this cheat sheet: https://docs.emmet.io/cheat-sheet/

(or at the very least bookmark it for later)

๐Ÿ“ Task 11: Try out Emmet
  1. Test out Emmet
    • try the single exclamation mark: !
    • try the triple exclamation mark !!!
  2. Recreate index.html using Emmet abbreviations
  3. Can you recreate index.html with a single Emmet abbreviation?

11. Marking Off

This lab is worth marks. be sure to get signed off.