HTML, CSS, JavaScript Basics

Chapter 4
HTML Content, Media, Tables and Forms

Bachelors Program in Full Stack Development
HTML, CSS, JavaScript Basics   •   Bachelor

HTML Content, Media, Tables and Forms

Introduction and Context

HTML (HyperText Markup Language) provides the semantic structure of a web document. While CSS controls presentation and JavaScript supports behaviour, HTML defines what content means: a heading, image, table, navigation region, user input, or submitted value. This semantic role is important for accessibility, search-engine interpretation, maintainability, responsive design, and interaction with browsers and assistive technologies.

Modern web pages are rarely composed only of text. They commonly contain photographs, illustrations, audio, video, data tables, registration forms, search controls, and transactional interfaces. These elements must be implemented in ways that remain usable across screen sizes, input devices, browsers, and accessibility tools. The objective is therefore not merely to make content appear on screen, but to communicate its purpose and support reliable user interaction.

This chapter examines HTML content, media, tables, and forms, with particular attention to semantics, responsive behaviour, accessibility, validation, and submission concepts.

Learning Objectives

By the end of this chapter, students should be able to:

1. Select appropriate HTML elements for text and structured content.

2. Implement accessible images, responsive media, audio, and video.

3. Construct tables with meaningful headings and captions.

4. Design forms using suitable controls, labels, constraints, and validation.

5. Explain how form data is submitted and processed.

6. Evaluate an interface for usability, accessibility, responsiveness, and maintainability.

1. Semantic HTML Content

1.1 Content structure

HTML elements communicate relationships between content. Common structural elements include:

  • `<h1>` to `<h6>` for headings, arranged as a logical hierarchy.
  • `<p>` for paragraphs.
  • `<ul>` for unordered lists and `<ol>` for ordered lists.
  • `<li>` for list items.
  • `<blockquote>` for an extended quotation.
  • `<strong>` for strong importance and `<em>` for emphasis.
  • `<figure>` and `<figcaption>` for self-contained content with a caption.
  • `<section>` for a thematic grouping and `<article>` for independently distributable content.

A heading should be chosen for its structural level rather than its visual size. CSS can make an `<h2>` appear larger or smaller, but changing an element merely to obtain a desired appearance damages document structure. A page normally has one main `<h1>`, followed by headings that represent nested topics.

The `<div>` and `<span>` elements are generic containers. They have no inherent semantic meaning and should be used when no more suitable element exists. Excessive use of generic containers makes documents harder to understand and can reduce accessibility.

1.2 Links and destinations

A hyperlink uses the `<a>` element and its `href` attribute:

```html

<a href="/courses/web-development">Web Development courses</a>

```

Link text should describe the destination or action. Text such as “click here” gives little information when links are listed by a screen reader. If a link opens a new browsing context, users should be informed where appropriate. The `target="_blank"` pattern should be used cautiously; links opening a new tab can be disorienting, particularly for users relying on assistive technology.

2. Images and Responsive Media

2.1 Images and alternative text

The basic image element is:

```html

<img src="campus.jpg" alt="Students working together in a campus laboratory">

```

The `src` attribute identifies the resource. The `alt` attribute provides a text alternative when the image cannot be seen or loaded. Alternative text should communicate the image’s purpose, not mechanically describe every visual detail.

Useful decisions include:

  • A meaningful photograph needs concise descriptive alternative text.
  • A decorative image should normally use `alt=""`, allowing assistive technology to ignore it.
  • An image containing essential text should provide that text in the alternative or, preferably, as real HTML text.
  • An image functioning as a link should describe the link’s destination or action.

The `width` and `height` attributes can reserve layout space and reduce cumulative layout shift:

```html

<img src="lab.jpg" alt="A student testing a circuit" width="1200" height="800">

```

CSS commonly limits an image to its container:

```css

img {

max-width: 100%;

height: auto;

}

```

`height: auto` preserves the image’s intrinsic aspect ratio when its width is changed. Developers should also compress images, choose suitable formats, and avoid sending very large files to small screens.

2.2 Figure and caption

When an image is referenced by surrounding content, `<figure>` and `<figcaption>` provide a semantic relationship:

```html

<figure>

<img src="network-topology.png" alt="Three computers connected to a central switch">

<figcaption>Illustrative small-office network topology.</figcaption>

</figure>

```

The caption is not a replacement for alternative text. The alternative text describes the image for users who cannot see it; the caption identifies or explains it for all users.

2.3 Responsive images

Different devices may require different image dimensions or crops. The `srcset` and `sizes` attributes allow the browser to select an appropriate resource:

```html

<img

src="course-800.jpg"

srcset="course-400.jpg 400w, course-800.jpg 800w, course-1400.jpg 1400w"

sizes="(max-width: 600px) 100vw, 70vw"

alt="Instructor demonstrating a web application">

```

The width descriptors (`400w`, `800w`, and `1400w`) state the intrinsic widths of candidate files. The `sizes` attribute gives the browser an estimate of the rendered width. This can reduce bandwidth while preserving visual quality.

The `<picture>` element is useful when art direction or format selection is required:

```html

<picture>

<source media="(max-width: 600px)" srcset="portrait-crop.jpg">

<source type="image/avif" srcset="campus.avif">

<img src="campus.jpg" alt="Main university campus building">

</picture>

```

The fallback `<img>` is required. A source element is not itself displayed content; it provides selection instructions.

3. Audio and Video

HTML provides native media elements, avoiding the need for a proprietary plug-in in ordinary cases.

```html

<audio controls>

<source src="lecture.mp3" type="audio/mpeg">

<source src="lecture.ogg" type="audio/ogg">

Your browser does not support the audio element.

</audio>

```

The `controls` attribute exposes browser controls. Autoplay should generally be avoided, especially with sound, because unexpected audio can disrupt users and create accessibility problems. If autoplay is genuinely necessary, muted playback and an obvious control to stop or pause it are important considerations.

Video is implemented similarly:

```html

<video controls width="960" poster="lecture-poster.jpg">

<source src="lecture.mp4" type="video/mp4">

<track src="lecture-en.vtt" kind="subtitles" srclang="en" label="English" default>

Your browser does not support the video element.

</video>

```

Important video practices include:

  • Provide captions for spoken dialogue and meaningful sounds.
  • Offer a transcript when feasible.
  • Provide sufficient controls for pause, volume, seeking, and fullscreen use.
  • Use a `poster` image to represent the video before playback.
  • Avoid flashing content that could trigger photosensitive seizures.
  • Consider bandwidth, encoding, and mobile data costs.

The `<track>` element commonly uses WebVTT (`.vtt`) files for captions. Captions are not only an accommodation for deaf or hard-of-hearing users; they help in noisy environments, quiet workplaces, second-language learning, and situations in which sound is unavailable.

4. Tables and Structured Data

Tables are appropriate for data that has meaningful row-and-column relationships, such as a timetable, price list, or examination schedule. They should not be used to position unrelated page elements; CSS layout systems such as Flexbox and Grid are intended for layout.

A basic accessible table is:

```html

<table>

<caption>Semester examination schedule</caption>

<thead>

<tr>

<th scope="col">Course</th>

<th scope="col">Date</th>

<th scope="col">Room</th>

</tr>

</thead>

<tbody>

<tr>

<th scope="row">Web Development</th>

<td>12 June</td>

<td>B204</td>

</tr>

<tr>

<th scope="row">Database Systems</th>

<td>15 June</td>

<td>C101</td>

</tr>

</tbody>

</table>

```

The `<caption>` names the table. `<thead>`, `<tbody>`, and `<tfoot>` group rows. Header cells use `<th>`, while data cells use `<td>`. The `scope` attribute clarifies whether a header labels a column or row. For complex tables involving multiple levels of headers, the `id` and `headers` attributes may be needed to express exact associations.

Tables should remain readable on narrow screens. Possible strategies include allowing horizontal scrolling within a labelled container, transforming rows into cards with careful CSS, or presenting a simplified mobile view. Hiding important columns without providing an alternative is not an acceptable responsive solution.

5. Forms: Controls, Labels and Structure

Forms collect data and initiate actions. A form is commonly structured as follows:

```html

<form action="/enrol" method="post">

<fieldset>

<legend>Student details</legend>

<label for="student-name">Full name</label>

<input id="student-name" name="studentName" type="text" autocomplete="name" required>

<label for="student-email">University email</label>

<input id="student-email" name="email" type="email" autocomplete="email" required>

<button type="submit">Submit enrolment</button>

</fieldset>

</form>

```

The `action` identifies the submission endpoint. The `method` specifies how the browser sends data. `post` is generally appropriate for creating or changing server-side data; `get` is useful for safe, repeatable requests such as searches, where values become part of the URL.

Every control should have a visible, meaningful label. The `for` value of a `<label>` must match the control’s `id`. The `name` attribute is equally important: it identifies the field name in submitted data. An input with an `id` but no `name` is not normally included in a successful form submission.

5.1 Choosing controls

HTML provides controls with different semantics:

  • `text`: general single-line text.
  • `email`: an email-oriented input and mobile keyboard hint.
  • `password`: obscures entry on screen.
  • `number`: numerical input where spinner behaviour is suitable.
  • `date`: a date value using a browser-supported date picker.
  • `radio`: one selection from a group sharing the same `name`.
  • `checkbox`: independent Boolean choices or multiple selections.
  • `file`: file selection from the user’s device.
  • `<textarea>`: multiline text.
  • `<select>`: selection from a predefined list.
  • `<button>`: an explicit action.

Radio buttons should be grouped with `<fieldset>` and labelled with `<legend>`:

```html

<fieldset>

<legend>Preferred study mode</legend>

<label><input type="radio" name="mode" value="campus" required> Campus</label>

<label><input type="radio" name="mode" value="online"> Online</label>

</fieldset>

```

A group of related checkboxes may use the same fieldset, while each checkbox normally has a distinct `name` and `value`.

5.2 Help text and errors

Instructions should be close to the relevant control. `aria-describedby` can associate supplementary text with an input:

```html

<label for="password">Password</label>

<input id="password" name="password" type="password"

aria-describedby="password-help" required>

<p id="password-help">Use at least 12 characters.</p>

```

Error messages should identify the field, explain the problem, and state how to correct it. Colour alone should not communicate an error. The field should retain the user’s valid entries after a failed submission, and focus should be moved appropriately so keyboard and screen-reader users can find the problem.

6. Constraints and Validation

Client-side validation provides immediate feedback and prevents obviously invalid submissions. Common constraints include:

```html

<input type="text" name="username" minlength="3" maxlength="20" required>

<input type="number" name="credits" min="1" max="40" step="1" required>

<input type="email" name="email" required>

<input type="text" name="code" pattern="[A-Z]{2}[0-9]{4}" required>

```

Important attributes include:

  • `required`: a value must be supplied.
  • `minlength` and `maxlength`: text length limits.
  • `min`, `max`, and `step`: numeric or date constraints.
  • `pattern`: a regular-expression constraint for suitable text values.
  • `type`: supplies semantic expectations and built-in browser validation.
  • `autocomplete`: helps users complete familiar information efficiently.

The `placeholder` attribute is not a label. Placeholder text disappears during entry, can have poor contrast, and should not be used to communicate essential instructions.

HTML constraint validation is useful but is not a security boundary. A malicious or modified client can bypass it, and different browsers may present different messages. The server must independently validate type, length, range, format, authorisation, and business rules. Server-side validation should also use parameterised database queries and appropriate output encoding to reduce injection and cross-site scripting risks.

JavaScript can enhance validation, for example by displaying a custom message, but it should not be required for basic form operation. The Constraint Validation API includes methods such as `checkValidity()` and `setCustomValidity()`. Custom validation must not replace clear native semantics or create inaccessible error handling.

7. Submission Concepts and Security

When a form is submitted, the browser constructs a set of successful controls: generally enabled controls with a `name` and a value. Unchecked checkboxes and unselected radio groups may contribute no value. The server receives the data, validates it, performs an operation, and returns a response.

With `method="get"`, data is encoded in the URL, for example as a query string. GET is appropriate for retrieval and search because requests can be bookmarked and repeated. Sensitive data should not be placed in a URL. With `method="post"`, data is sent in the request body. POST is suitable for operations that create or modify server state, but it does not by itself encrypt data.

Secure form processing normally requires HTTPS, server-side validation, authentication and authorisation where relevant, protection against cross-site request forgery, safe file-upload handling, rate limiting for sensitive operations, and careful privacy practices. Passwords must never be stored as plain text; servers should use established password-hashing mechanisms. Forms should collect only data necessary for a legitimate purpose, explain its use, and provide appropriate retention and deletion practices.

8. Accessibility and Inclusive Design

Accessible HTML begins with native semantics. A correctly labelled `<button>` is normally preferable to a clickable `<div>` because it provides keyboard interaction and role information automatically. Images need appropriate alternatives, multimedia needs captions or transcripts, tables need header relationships, and forms need labels and understandable errors.

Keyboard testing should verify that users can reach every interactive element, identify focus, operate controls, and submit the form without a mouse. Focus indicators should remain visible. Colour contrast should be adequate, but accessibility should not be reduced to contrast alone. Interfaces should also consider screen magnification, touch targets, cognitive load, language, motion sensitivity, and variable network conditions.

ARIA (Accessible Rich Internet Applications) can supplement HTML when native semantics are insufficient. It should not be used to repair an avoidable misuse of a native element. A practical principle is: use semantic HTML first, add ARIA only when a tested interaction genuinely requires it.

9. Worked Example: An Accessible Course Enrolment Form

Consider a university enrolment page requiring a student’s name, email, study mode, preferred start date, and a short statement.

```html

<form action="/enrol" method="post">

<h2>Course enrolment</h2>

<label for="name">Full name</label>

<input id="name" name="name" type="text" autocomplete="name"

minlength="2" required>

<label for="email">Email address</label>

<input id="email" name="email" type="email" autocomplete="email" required>

<fieldset>

<legend>Study mode</legend>

<label><input type="radio" name="mode" value="campus" required> Campus</label>

<label><input type="radio" name="mode" value="online"> Online</label>

</fieldset>

<label for="start">Preferred start date</label>

<input id="start" name="startDate" type="date" required>

<label for="statement">Why are you interested in this course?</label>

<textarea id="statement" name="statement" maxlength="500"

aria-describedby="statement-help" required></textarea>

<p id="statement-help">Write no more than 500 characters.</p>

<label>

<input type="checkbox" name="updates" value="yes">

Send me course updates

</label>

<button type="submit">Submit application</button>

</form>

```

The form uses labels, meaningful names, a fieldset for the radio group, native types, constraints, autocomplete, and help text. A production system must additionally validate the submitted date and statement on the server, protect the endpoint, store data according to institutional policy, and provide accessible error responses.

10. Illustrative Case Study: Responsive Department Information Page

Background

A fictional university department publishes a page containing a campus photograph, a timetable, a recorded welcome message, and an enquiry form. The original page uses a large uncompressed image, a table without headings, an autoplaying video, and inputs identified only by placeholder text.

Problem

Mobile users experience slow loading and horizontal scrolling. Screen-reader users cannot determine table relationships or form purposes. The video begins unexpectedly, and invalid submissions produce no understandable feedback.

Analysis

The problems are not primarily aesthetic. They arise from missing semantics, excessive resource size, inadequate responsive design, and weak validation and error communication. They also create institutional risks: applicants may abandon the form, and users with disabilities may be excluded.

Approach and solution

The development team replaces the generic image with a responsive `<picture>` implementation and useful alternative text. The timetable receives a caption, header cells, row and column scopes, and a mobile scrolling strategy. The video uses controls, a poster, captions, and a transcript; autoplay is removed. Each form control receives a visible label, a stable `id`, a submission `name`, suitable input types, and constraints. Server-side validation and accessible error summaries are added. The page is tested with keyboard navigation, a screen reader, narrow viewport sizes, slow network simulation, and multiple browsers.

Outcome

The page becomes faster on mobile, its data is understandable through assistive technology, and users receive predictable feedback. The team also gains a reusable component standard for future departmental pages.

Learning points

1. Semantics improve both accessibility and maintainability.

2. Responsive media is a performance and inclusion concern, not merely a visual preference.

3. Client-side validation improves interaction, but server-side validation remains essential.

4. Testing with real interaction modes reveals defects that visual inspection can miss.

11. Contemporary Practice and Professional Implications

Modern interfaces increasingly combine semantic HTML with responsive CSS, progressive enhancement, content-management systems, and component-based JavaScript frameworks. Frameworks do not eliminate the need to understand HTML; poorly configured components can produce inaccessible controls, incorrect focus behaviour, and invalid form states.

Performance budgets, responsive image selection, lazy loading where appropriate, and efficient media encoding are important professional practices. However, lazy loading should not delay essential above-the-fold content, and media should not be optimised at the expense of clarity or accessibility.

AI-assisted coding tools can generate HTML quickly, but generated code requires human review. Common risks include missing alternative text, inappropriate ARIA, weak labels, invalid nesting, insecure form handling, and collection of unnecessary personal data. Developers remain accountable for testing, standards compliance, privacy, and user impact.

Challenges and Limitations

HTML’s native controls differ slightly across browsers and operating systems, especially date pickers, validation messages, and media controls. Custom controls may provide a consistent visual design but require substantial keyboard, focus, semantics, and assistive-technology work. Native controls should therefore be preferred unless a documented requirement justifies replacement.

Accessibility cannot be guaranteed by markup alone. CSS can hide focus or create poor contrast, JavaScript can break keyboard interaction, and server responses can discard user input. Quality assurance must examine the complete system and include users with diverse abilities and devices.

Best-Practice Checklist

  • Use semantic elements before generic containers.
  • Provide purposeful alternative text for images.
  • Use responsive image techniques and efficient media files.
  • Give audio and video controls, captions, and transcripts where appropriate.
  • Use tables only for relationships that are genuinely tabular.
  • Provide captions and correctly associated table headers.
  • Give every form control a visible label and a submission name.
  • Group related controls with `fieldset` and `legend`.
  • Use native input types and constraints where suitable.
  • Validate on both client and server.
  • Preserve user input and explain errors clearly.
  • Test keyboard access, screen-reader output, mobile layouts, and slow networks.
  • Protect personal data and secure form-processing endpoints.

Chapter Summary

HTML provides the semantic foundation for content, media, data, and user interaction. Images require appropriate alternative text, responsive sizing, and efficient resources. Audio and video should provide controls and, where relevant, captions and transcripts. Tables are for structured relationships and should use captions, header cells, and scope information. Forms depend on suitable controls, visible labels, meaningful `name` attributes, grouping, constraints, and clear error communication. GET and POST represent different submission purposes, while all submitted data requires independent server-side validation and security controls. Accessible, responsive implementation is achieved through semantic HTML, progressive enhancement, systematic testing, and attention to privacy and inclusion.

Key Terms

Semantic HTML: HTML whose elements communicate the meaning and role of content.

Alternative text: Text that conveys an image’s purpose when the image cannot be perceived.

Responsive image: An image implementation that selects or sizes resources according to device and context.

`srcset`: An image attribute listing alternative resources for browser selection.

`picture`: An element supporting responsive source selection and art direction.

Caption: Text accompanying media or a table to identify or explain it.

Transcript: A text representation of spoken or meaningful audio content.

Table header: A `<th>` cell that identifies a row or column.

Scope: An attribute indicating whether a table header describes a row or column.

Form control: An interactive element used to collect or submit data.

Label: Text programmatically associated with a form control to communicate its purpose.

Constraint validation: Checking whether submitted or entered data satisfies defined rules.

`required`: A constraint indicating that a value must be supplied.

Autocomplete: A hint that helps browsers fill familiar user information.

GET: A request method commonly used for retrieval and query parameters.

POST: A request method commonly used to send data for processing or state change.

Progressive enhancement: Building a functional baseline first and adding richer features where supported.

ARIA: A set of attributes that supplements accessibility semantics when native HTML is insufficient.

Successful control: An enabled, named form control whose value is included in submission.

Server-side validation: Independent validation performed by the receiving application.

Review Questions

Short Answer Questions

1. Why is alternative text required for meaningful images?

2. What is the purpose of the `scope` attribute in a data table?

3. Why must a form control normally have a `name` attribute?

4. Distinguish client-side validation from server-side validation.

5. Why should placeholder text not replace a visible label?

Long Answer Questions

1. Explain how semantic HTML supports accessibility, search interpretation, and maintainability.

2. Describe a complete strategy for implementing responsive and accessible video content.

3. Compare GET and POST form submission, including appropriate uses and security considerations.

4. Explain how to design an accessible form with labels, fieldsets, constraints, help text, and errors.

5. Discuss why tables should not be used for page layout and explain how a data table can be made responsive.

Analytical / Application Questions

1. Audit a registration form that uses only placeholders, lacks `name` attributes, and validates only in JavaScript. Identify the risks and propose corrections.

2. Design an HTML structure for a course page containing a responsive hero image, a timetable, a captioned welcome video, and an enquiry form. Justify the semantic element selected for each part.

3. A department page is unusable on mobile because of a large image, a wide table, and autoplaying audio. Develop a prioritised remediation plan addressing performance, accessibility, and user experience.

Multiple Choice Questions with Answers

Question 1

Which attribute provides a text alternative for an image?

A. title

B. alt

C. caption

D. describe

Correct Answer: B. alt

Question 2

Which element semantically groups a table’s descriptive title?

A. legend

B. summary

C. caption

D. label

Correct Answer: C. caption

Question 3

What is the primary purpose of the name attribute on a form control?

A. To determine its CSS colour

B. To identify its submitted field name

C. To provide visible help text

D. To make it keyboard accessible

Correct Answer: B. To identify its submitted field name

Question 4

Which element is most appropriate for a group of related radio buttons?

A. fieldset with legend

B. div with placeholder

C. table with caption

D. section with poster

Correct Answer: A. fieldset with legend

Question 5

Which input type supplies email-oriented semantics and validation?

A. text

B. mailbox

C. email

D. address

Correct Answer: C. email

Question 6

Why is server-side validation necessary when HTML constraints are used?

A. Browsers cannot display labels

B. Client-side checks can be bypassed

C. HTML forms cannot use POST

D. CSS removes invalid values

Correct Answer: B. Client-side checks can be bypassed

Question 7

Which method is generally suitable for a bookmarkable search request?

A. POST

B. PATCH

C. GET

D. CONNECT

Correct Answer: C. GET

Question 8

What should normally be provided for spoken content in an instructional video?

A. A larger poster only

B. Captions

C. A decorative image only

D. Autoplay

Correct Answer: B. Captions

Question 9

Which element identifies a row or column header in a table?

A. td

B. th

C. tr

D. thead-only

Correct Answer: B. th

Question 10

What is the main benefit of using srcset for images?

A. It submits image data to a server

B. It prevents all image compression

C. It lets the browser select an appropriate resource

D. It converts images into tables

Correct Answer: C. It lets the browser select an appropriate resource

HTML, CSS, JavaScript Basics
Chapter 4 of 15