Tables

The <table> Element

The <table> element is a powerful tool for web designers:

  • Tables allow us to display information in a predictable and uniform fashion on a web page.
  • Tables are well suited for presenting data that conforms to rows and columns.
  • Content in table cells is easy to format consistently.

In the past, tables were often used to lay out and organize an entire web page.  This was a misuse of the <table> element, which should be used only to present specific information within a page’s overall content.

Rows and Columns

Rows and Columns
This simple table has two columns and three rows.

Building an XHTML Table
tables

<table> </table> Establishes the table on the web page.
<tr> </tr> Defines a new table row, which spans
the available width of the table.
<td> </td> Defines a cell of table data within a row.
The <td> cells will evenly share the
horizontal space in a row.
If there is just one <td> element in a row,
it will use the entire width available.

In this code, we have created a table and defined three table rows, each with two cells of table data (i.e. two columns).
table-text

Adding Table Data
table-dataHere we have added meaningful data to the table and it is displayed on our web page, though the table is not very visually appealing.

Defining a Border
definin-borderBy adding the border=”1″ attribute to the table element, browsers will display the table with vertical and horizontal borders around each cell.  This makes the table a bit easier to view.

Specifying Table Headers
specify-header
If the text in our top row is meant to serve as column labels for the data below, we can use the <th> (“table header”) element instead of regular <td> elements.  This informs the browser to automatically bold and center the text.
header-table

Spanning Rows and Columnsspan-row-colExample: Spanning Columns
We can build a data cell that spans more than one column by using the colspan attribute:colspanThe value placed in the colspan attribute informs the browser how many columns to combine into a single data cell.

Example: Spanning RowsrowspanThe rowspan attribute works the same way by informing the browser how many rows to combine into a single cell.

Example: Spanning Rows and ColumnscolrowBoth the colspan and rowspan features can be used in the same table to create a more complex table structure.

Adding a Table Captiontable-captionTo add a caption to the table, we use the <caption> element immediately after the opening <table> tag.  The text enclosed within the <caption> element will be displayed above the table and centered.

Other Elements Inside Tablesother-elements-tablesMany other elements can be placed inside table cells, including paragraphs, links, images, lists, and even other tables.