HTMLLesson 6 of 10Jump to practice

Tables

Show data in rows and columns with table, tr, th and td.

Use a table when your data has rows and columns, like a timetable, a price list or exam results.

Element Meaning
<table> The whole table
<tr> A table row
<th> A header cell (bold and centered by default)
<td> A data cell
<caption> A title for the table

A table is built row by row. Each <tr> holds its cells from left to right.

Exam results
Open in editor
<!DOCTYPE html>
<html>
<head>
<style>
  table { border-collapse: collapse; }
  th, td { border: 1px solid #999; padding: 6px 12px; }
</style>
</head>
<body>
<table>
  <caption>Class test results</caption>
  <tr>
    <th>Name</th>
    <th>English</th>
    <th>Math</th>
  </tr>
  <tr>
    <td>Emma</td>
    <td>78</td>
    <td>91</td>
  </tr>
  <tr>
    <td>Diego</td>
    <td>85</td>
    <td>74</td>
  </tr>
</table>
</body>
</html>
Result

Tables have no borders by default. The small <style> block above adds them. You’ll learn how that works in the CSS course.

Larger tables group their rows into <thead>, <tbody> and <tfoot>. This doesn’t change how the table looks, but it tells the browser which rows are headings and which are totals.

Cells that span

colspan="2" makes a cell two columns wide. rowspan="2" makes it two rows tall.

Grouped rows and a spanning cell
Open in editor
<!DOCTYPE html>
<html>
<head>
<style>
  table { border-collapse: collapse; }
  th, td { border: 1px solid #999; padding: 6px 12px; text-align: left; }
  tfoot { font-weight: bold; }
</style>
</head>
<body>
<table>
  <thead>
    <tr><th>Item</th><th>Price</th></tr>
  </thead>
  <tbody>
    <tr><td>Notebook</td><td>$3</td></tr>
    <tr><td>Pen</td><td>$1</td></tr>
  </tbody>
  <tfoot>
    <tr><td colspan="2">Total: $4</td></tr>
  </tfoot>
</table>
</body>
</html>
Result

Practice

Check what you just learned. Fill in the missing code, then answer the quiz.

  1. Exercise 1

    Each row of a table uses one element. Fill it in.

    <table>
      <>
        <td>Apple</td>
        <td>$1.25</td>
      </>
    </table>

  2. Exercise 2

    Make these header cells, so browsers and screen readers know they label the columns.

    <tr>
      <>Fruit</>
      <th>Price</th>
    </tr>

  3. Exercise 3

    Make this cell stretch across two columns.

    <tr>
      <td ="2">Total: 240</td>
    </tr>

Quiz: 3 questions

1. What does <td> hold?
2. Should you use a table to lay out a whole web page?
3. Which element gives a table a visible title?

Finish the practice to complete this lesson.