This page explores the use of html tables as described in the HTML 4 specification.
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:
Cell 1 | Cell 2 |
Cell 3 | Cell 4 |
<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:
Column 1 | Column 2 |
---|---|
Cell 1 | Cell 2 |
Cell 3 | Cell 4 |
<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:
Row # | Column 1 | Column 2 |
---|---|---|
1 | Cell 1 | Cell 2 |
2 | Cell 3 | Cell 4 |
<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:
Column Headings | ||
---|---|---|
Row # | Column 1 | Column 2 |
1 | Cell 1 | Cell 2 |
2 | Cell 3 | Cell 4 |
<table>
<caption>Example table ... </caption>
<thead>
<tr><th> </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.