Tables in HTML are a great way for displaying data that can be looked up using the row and columns.
Historically, tables have been used historically for maintaining the layout of HTML pages. Using tables for layout is now conidered bad practice, and causes issues with the accessibility of websites.
Tables should only ever be used where we want to display data that can be looked up by row and column, as in the example below
The key elements used to construct a table are as follows:
<table>
- defines the table<tbody>
- used to contain the table data (in rows and cells)<tfoot>
- optionally used to define any table footer information. Contrary to what one might expect, if used this needs to come after the table header element, but before the body of the table<thead>
- optionally used to define table header information, for example column titles<th>
- a table header cell - used for displaing a cell of data inside a table header<tr>
- a table row, used inside the head, foot or body and contains a number of data items (cells)<td>
- a table data item (cell) this must be inside a row<table>
<thead>
<tr><th>Name</th><th>Phone</th><th>Office</th></tr>
</thead>
<tbody>
<tr><td>Andrew</td><td>3098</td><td>TAS033</td></tr>
<tr><td>Adam</td><td>1668</td><td>CML010</td></tr>
<tr><td>Matt</td><td>1296</td><td>CML007</td></tr>
</tbody>
</table>
This will render in a similar way to that shown below, though by default the browser may add some grid lines:
Name | Phone | Office |
---|---|---|
Andrew | 3098 | TAS033 |
Adam | 1668 | CML010 |
Matt | 1296 | CML007 |
You may wish to write <td>
elements on a new line to make reading your code easier, this is fine, as the web browser will ignore the extra lines.