Exploring Tables – The Basics

This page explores the use of html tables as described in the HTML 4 specification.

Simple Tables in HTML 4:

The simplest table consists of the TABLE element itself and, at a minimum, one or more table cells denoted by TD elements contained within one or more TR (table row) elements:

Example 1:

Cell 1Cell 2
Cell 3Cell 4

Markup:

<table>
  <tr><td>Cell 1<td>Cell 2
  <tr><td>Cell 3<td>Cell 4
</table>

Note that each element is denoted in the page source (markup) by the relevant opening tags (<table>, <tr>, and <td>). The closing tags for TR and TD are optional, since these are inferred from the next opening tag.

Since it is helpful to provide headings for each column, TH elements are also defined. The advantage of using TH elements is that these are generally styled differently to the TD elements automatically by browsers, so that the column headings are visually distinct and easily identified:

Example 2:

Column 1Column 2
Cell 1Cell 2
Cell 3Cell 4

Markup:

<table>
  <tr><th>Column 1<th>Column 2
  <tr><td>Cell 1<td>Cell 2
  <tr><td>Cell 3<td>Cell 4
</table>

We can also use TH elements to label individual rows:

Example 3:

Row #Column 1Column 2
1Cell 1Cell 2
2Cell 3Cell 4

Markup:

<table>
  <tr><th>Row #<th>Column 1<th>Column 2
  <tr><th>Row 1<td>Cell 1<td>Cell 2
  <tr><th>Row 2<td>Cell 3<td>Cell 4
</table>

Some tables can have complex structures, where we might want headers and sub-headers for certain columns. Table rows can therefore be grouped using a THEAD and a TBODY element, which provides more structural clarity in the page markup. We can also explicitly include closing tags even when inferred, as this can make editing complex tables easier:

Example 4:

Example table using colspan and caption
 Column Headings
Row #Column 1Column 2
1Cell 1Cell 2
2Cell 3Cell 4

Markup:

<table>
  <caption>Example table ... </caption>
  <thead>
    <tr><th>&nbsp;</th><th colspan="2">Column Headings</th></tr>
    <tr><th>Row #</th><th>Column 1</th><th>Column 2</th></tr>
  </thead>
  <tbody>
    <tr><th>1</th><td>Cell 1</td><td>Cell 2</td></tr>
    <tr><th>2</th><td>Cell 3</td><td>Cell 4</td></tr>
  </tbody>
</table>

Note the use of the colspan attribute: setting this to 2 specifies that this particular TH should span two adjacent columns; there is also a corresponding rowspan attribute. These attributes can also be set on TD cells.

This example also uses the caption element to add a label to the table. The specification states that this must follow the opening <table> tag in the markup. The default position is at the top of the table (i.e. above the table header).

So far, we have only looked at the markup and structure of tables without being greatly concerned about their appearance. The next page introduces table formatting and appearance.