L2: HTML

Claude prompt: extract everything possible and most useful for writing html for my midterm from this presentation, i rely on you heavily but make it also in a very compact format

HTML Midterm Study Guide — INF2040B Lecture 02


1. HTML Basics

  • HTML = HyperText Markup Language; structures web content using tags/elements

  • HTML5 = latest version; adds semantic elements, native audio/video, APIs, no plugins needed

  • History: Tim Berners-Lee 1991 → HTML5 draft 2008 → W3C Recommendation 2014


2. HTML5 vs HTML4 vs XHTML

Feature

HTML5

HTML4

XHTML

Doctype

<!DOCTYPE html> (simple)

Long doctype

Long doctype

Tags case

Case-insensitive

Case-insensitive

Lowercase required

Closing tags

Optional for some

Optional

All must be closed

Self-closing

<br> OK

<br> OK

<br/> required

Attribute quotes

Optional

Optional

Required

Error handling

Forgiving

Forgiving

Strict — breaks on error

Media type

text/html

text/html

application/xhtml+xml

Script/style type

Not needed

Needed

Required

Semantic elements

New

XHTML = HTML + XML strict rules. Mostly obsolete; modern dev uses HTML5.


3. HTML5 Document Structure

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Page Title</title>
  </head>
  <body>
    <!-- content -->
  </body>
</html>

4. Elements by Category

Document Structure

Tag

Purpose

<html>

Root element

<head>

Metadata container (title, meta, link, style, script)

<body>

All visible content

Content Sectioning (Semantic)

Tag

Purpose

<header>

Intro content / nav links

<nav>

Navigation links

<main>

Main content of page

<article>

Self-contained content (blog post, news)

<section>

Thematic grouping

<aside>

Indirectly related content (sidebar)

<footer>

Footer (author, copyright, links)

<h1><h6>

Headings (h1 = highest)

<hgroup>

Groups multi-level headings

Text & Formatting

Tag

Purpose

<p>

Paragraph

<b>

Bold — visual only, no semantic meaning

<strong>

Bold — semantic: important/urgent

<i>

Italic — different voice/mood, no emphasis

<em>

Italic — semantic: stressed emphasis

<code>

Inline code

<blockquote>

Block quotation from another source

<br>

Line break (self-closing; <br/> in XHTML)

<hr>

Thematic break / horizontal rule

<address>

Contact info for author/org

<span>

Generic inline container (for CSS/JS)

Key distinction: <b> vs <strong> — both bold visually, but <strong> signals importance to screen readers/SEO. Same logic: <i> vs <em>.

Links & Navigation

Tag

Key Attribute

Purpose

<a>

href

Hyperlink

<link>

rel, href

External resource (e.g., stylesheet)

<map>

name

Image map container

<area>

shape, coords, href

Clickable region in image map

<area> shape options: rect, circle, poly, default rect coords: x1,y1,x2,y2 (top-left to bottom-right)

Lists

Tag

Purpose

<ul>

Unordered list

<ol>

Ordered list

<li>

List item (used in both)

<menu>

Group of commands (rarely used)

Tables

Tag

Purpose

<table>

Table container

<caption>

Table title (goes right after <table>)

<thead>

Header rows group

<tbody>

Body rows group

<tfoot>

Footer rows group

<tr>

Table row

<th>

Header cell

<td>

Data cell

<colgroup>

Groups columns for formatting

<col>

Column properties inside <colgroup>

Forms & Input

Tag

Purpose

<form>

Form container

<input>

Input field (many types)

<label>

Label for input — for attr links to input id

<button>

Clickable button (type="submit" / type="reset")

<select>

Dropdown

<option>

Option in dropdown

<fieldset>

Groups related form elements

<legend>

Caption for <fieldset>

<datalist>

Autocomplete suggestions for <input>

HTML5 Input Types: text, password, email, url, number, range, date, checkbox, radio, file, submit, reset, color, search, tel

Media

Tag

Purpose

<img>

Image — requires src and alt

<audio>

Audio player — controls attribute

<video>

Video player — controls attribute

<source>

Multiple media sources for audio/video

<embed>

External content (PDFs, etc.) — self-closing

<iframe>

Embedded external page

Interactive / Advanced

Tag

Purpose

<canvas>

JS-drawn 2D/3D graphics

<details>

Expandable/collapsible content

<summary>

Caption/toggle for <details>

<dialog>

Modal dialog — methods: show(), showModal(), close()

Metadata

Tag

Purpose

<meta>

charset, viewport, description, keywords, author

<base>

Base URL for relative links (1 per doc, in <head>)

<script>

JavaScript (inline or src); defer / async attributes

<style>

Internal CSS

Containers / Misc

Tag

Purpose

<div>

Generic block container (layout, grouping)

<span>

Generic inline container


5. Key Attribute Distinctions

name vs id

name

id

Purpose

Form submission key

Unique element identifier

Uniqueness

Not required

Must be unique in doc

Used for

Server receives name=value

CSS/JS targeting, <label for="">

<label for="">

The for attribute must match the input's id. Clicking the label focuses the input — improves accessibility.


6. HTML Entities (Special Characters)

Entity

Character

&amp;

&

&lt;

<

&gt;

>

&quot;

"

&apos;

' (HTML5/XHTML)

&nbsp;

non-breaking space

&copy;

©

&reg;

®

&trade;

&mdash;

&hellip;

&times;

×

&divide;

÷

&euro;

&pound;

£


7. Semantic HTML — Why It Matters

  • Accessibility: Screen readers interpret structure correctly

  • SEO: Search engines rank structured content better

  • Readability: Other devs understand code easier

  • Use <article>, <section>, <header>, <footer> instead of plain <div> where appropriate

  • Proper heading hierarchy: <h1><h2><h3> (don't skip levels)


8. HTML5 APIs

Geolocation API

navigator.geolocation.getCurrentPosition(pos => {
  console.log(pos.coords.latitude, pos.coords.longitude);
});
  • Requires HTTPS + user permission

  • Uses GPS, Wi-Fi, cell triangulation

Web Storage API

// localStorage — persists after browser close
localStorage.setItem('key', 'value');
localStorage.getItem('key');

// sessionStorage — cleared when tab closes
sessionStorage.setItem('key', 'value');
  • Stores up to 5MB per domain (vs cookies)

Canvas API

const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
ctx.fillRect(10, 10, 100, 50);       // rectangle
ctx.arc(75, 75, 50, 0, Math.PI*2);   // circle
ctx.fill();

9. Canvas vs SVG

Canvas

SVG

Type

Bitmap (pixel-based)

Vector (XML-based)

Scaling

Loses quality

Scales perfectly

Use case

Games, animations, real-time graphics

Icons, logos, static illustrations

Manipulation

Via JS pixel operations

Via DOM/CSS


10. Shadow DOM / Web Components

  • Shadow DOM: Encapsulates HTML/CSS inside a component — styles don't leak in or out

  • Shadow Host: The element containing the shadow tree

  • Shadow Root: Entry point to shadow tree

    • mode: 'open' → accessible from JS outside

    • mode: 'closed' → cannot be accessed from outside

  • Global CSS doesn't affect shadow DOM internals

const shadow = element.attachShadow({ mode: 'open' });

Web Component parts: Custom Elements, Shadow DOM, HTML Templates


11. data-* Custom Attributes

  • Store custom metadata in HTML elements

  • Must start with data- prefix

  • Access via JS:

element.dataset.userId       // accesses data-user-id
element.getAttribute('data-user-id')

12. CORS (Cross-Origin Resource Sharing)

  • Browser security feature — blocks cross-domain requests by default (same-origin policy)

  • Server must send header: Access-Control-Allow-Origin: https://example.com or *

  • Simple requests (GET/POST) go directly; complex requests send a preflight OPTIONS request first


13. Responsive Web Design

  • Meta viewport tag (essential!):

<meta name="viewport" content="width=device-width, initial-scale=1.0">
  • Media queries in CSS for different screen widths

  • Flexbox / Grid for flexible layouts

  • Responsive images: <img srcset="...">


14. SEO Best Practices (HTML angle)

  • Use semantic tags (<article>, <section>, <header>)

  • <h1> = one per page, contains main keyword

  • <title> under 60 chars

  • <meta name="description"> under 160 chars

  • Descriptive alt attributes on all images

  • Clean, keyword-based URLs

  • HTTPS (Google ranking factor)

  • Mobile-friendly + fast load time


15. Quick Reference — Common Mistakes to Avoid

  • <b><strong> and <i><em> (semantics differ)

  • XHTML: all tags lowercase, all closed, all attributes quoted

  • <base> only one per doc, inside <head>

  • <caption> must immediately follow <table> tag

  • id must be unique; name doesn't have to be

  • <br> in HTML5 = <br> ; in XHTML = <br/>

  • <script> and <style> don't need type in HTML5 but do in XHTML

LABS

Problem 3: Create a navigation menu using the <nav> element

<body>
    <nav>
        <ul> 
            <li><a href = "#home">Home</a></li>
            <li><a href = "#contact"Contact</a></li>
        </ul>
    </nav>
    
</body>

Problem 4: Insert an image with alternate text

<body>
    <img src="image.jpg" alt="Our library">
</body>

Problem 5: Create a simple table with rows and headers

<body>
    <table>
        <thead>
            <tr>
                <th>Item</th>
                <th>Price</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <th>Pen</th>
                <th>$1</th>
            </tr>
            <tr>
                <th>Pencil</th>
                <th>$2</th>
            </tr>
        <tbody>

    <table>

</body>

Problem 6: Add a video element with controls.

<body>
    <video controls>
        <source src="video.mp4" type = "video/mp4"
        The video is not supported tag.
    </video>
</body>

Problem 7: Add an audio file with playback controls

<body>
    <audio controls> 
        <source src="audio.mp3" type="audio/mpeg"
        Your audio element is not supported.
    </audio>
</body>

Problem 8: Create a simple form with various input types

 First Name

 Last Name

 Age

 Hair Color

 Make the fields required

 Include proper validation for the age field

<body>
<h2>Personal Information Form</h2>
    
    <form action="/submit-form" method="POST">
        <!-- First Name field (required) -->
        <label for="firstname">First Name:</label>
        <input type="text" id="firstname" name="firstname" required><br><br>
        
        <!-- Last Name field (required) -->
        <label for="lastname">Last Name:</label>
        <input type="text" id="lastname" name="lastname" required><br><br>
        
        <!-- Age field (required, with min and max validation) -->
        <label for="age">Age:</label>
        <input type="number" id="age" name="age" min="1" max="120" required><br><br>
        
        <!-- Hair Color field (required - using dropdown instead of color picker) -->
        <label for="haircolor">Hair Color:</label>
        <select id="haircolor" name="haircolor" required>
            <option value="">Select hair color</option>
            <option value="black">Black</option>
            <option value="brown">Brown</option>
            <option value="blonde">Blonde</option>
            <option value="red">Red</option>
            <option value="gray">Gray</option>
            <option value="other">Other</option>
        </select><br><br>
        
        <!-- Submit button -->
        <input type="submit" value="Submit Form">
    </form>
</body>

Problem 9: Create a list of items (ordered and unordered)

<body>
    <h2>Unordored List</h2>
    <ul>
        <li>Item 1</li>
        <li>Item 2</li>
    </ul>

    <h2>OrderedList</h2>
    <ol>
        <li>First</li>
        <li>Second</li>
    </ol>
</body>

Problem 10: Embed a YouTube video using <iframe> - just copy all embed link from yt

<body>
    <iframe width="560" height="315" src="https://www.youtube.com/embed/xF-5ZD5e27A?si=NAcN_400KCT6si-U" title="YouTube video player" 
    frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</body>

Problem 11: Create a data list with predefined suggestions

<body>
    <label for="haircolor">Choose your hair Color:</label>
    <input list=""haircolors" id="haircolor" name="haircolor">
    <datalist id ="haircolors">
        <option value="black or brown">Black or Brown</option>
        <option value="ginger">Ginger</option>
        <option value="blonde">Blonde</option>
    </datalist>
           
</body>

Problem 12: Implement a <figure> with an image and caption

<body>
    <figure>
        <img src="image.jpg" alt="My cat">
        <figcaption>My cat at home<<figcaption>
    </figure>
</body>

Problem 13: Create a simple form validation using the required attribute

<body>
    <form> 
        <label for "username">Username: </label>
        <input type="text" id="username" name="username" required><br>
        <input type="submit" value="submit">
    </form>
</body>

Problem 14: Add an SVG image to your page

<body>
    <svg width="100" height="100">
        <circle cx="50" cy="50" r="40" stroke = "white" stroke-width="3" fill="red" />
    </svg>
</body>

Problem 15: Draw a Pie Chart with an SVG

<body>
    <svg width="200" height="200">
        <circle cx="100" cy="100" r="80" fill="red"/>
        <circle cx="100" cy="100" r="80" fill="blue" 
                style="clip-path: polygon(50% 50%, 100% 50%, 100% 100%, 50% 100%);"/>
    </svg>
    
</body>