11. HTML Tables

What you will learn

  • The elements that build a table
  • Header cells and captions
  • Merging cells with colspan and rowspan
  • When to use a table, and when not to

Table elements

Element Meaning
<table> The whole table
<tr> A table row
<th> A header cell (bold and centred by default)
<td> A normal data cell

A first table

Example

<table>
  <tr>
    <th>Name</th>
    <th>Age</th>
  </tr>
  <tr>
    <td>Sam</td>
    <td>25</td>
  </tr>
  <tr>
    <td>Ali</td>
    <td>31</td>
  </tr>
</table>

Output

Name Age
Sam 25
Ali 31

Read the table row by row. Each <tr> contains one cell per column.

Caption and table sections

Add a <caption> to describe the table. Group rows with <thead>, <tbody>, and <tfoot> so browsers and screen readers understand the structure.

Example

<table>
  <caption>Weekly study hours</caption>
  <thead>
    <tr><th scope="col">Day</th><th scope="col">Hours</th></tr>
  </thead>
  <tbody>
    <tr><td>Monday</td><td>2</td></tr>
    <tr><td>Tuesday</td><td>3</td></tr>
  </tbody>
  <tfoot>
    <tr><td>Total</td><td>5</td></tr>
  </tfoot>
</table>

Output

Weekly study hours
Day Hours
Monday 2
Tuesday 3
Total 5

The scope="col" attribute tells assistive technology that the header applies to the whole column.

Merging cells

colspan stretches a cell across several columns. rowspan stretches it across several rows.

Example

<table>
  <tr><th colspan="2">Contact</th></tr>
  <tr><td>Phone</td><td>555-0100</td></tr>
  <tr><td>Email</td><td>hi@example.com</td></tr>
</table>

Output

Contact
Phone 555-0100
Email hi@example.com

Borders and style

Tables have no borders by default. You add borders, spacing, and colours with CSS, which you will learn in the CSS course.

Use tables only for real data, such as schedules and price lists. Never use a table to arrange the layout of a page. Use CSS for layout.

Common mistakes

  • Using different numbers of cells in different rows without colspan or rowspan.
  • Forgetting </tr> or </td>.
  • Using <td> with bold text instead of <th> for headings.
  • Using a table for page layout.

Exercise

Create a table with two columns, Fruit and Colour, and one data row: Banana, Yellow.

Show solution
<table>
  <tr><th>Fruit</th><th>Colour</th></tr>
  <tr><td>Banana</td><td>Yellow</td></tr>
</table>

Knowledge check

1. Which element makes a header cell?

<th>

2. Which attribute makes a cell span two columns?

colspan="2"

3. Should you use tables for page layout?

No. Use them for data only.

Summary

  • Tables use <table>, <tr>, <th>, and <td>.
  • Add a caption and group rows for accessibility.
  • Merge cells with colspan and rowspan.
Scroll to Top