Add a table to your web page

Tables are added to present data; something HTML has allowed us to do this since its first versions. XHTML or HTML tables do not present any important variants, so this will be fast:

Tables are created with the <table> tag. This one is used to allow a few attributes, but only one, border="", will continue from HTML 5 onwards. The results others give can also be achieved using style sheets, so I will talk about them when talking about style sheets. By now, you should know that the border="" attribute defines whether both the table and its cells will have a border or not.

On HTML and XHTML, you use border="" to define the table's border width using a plain number to define the width. On HTML 5, border="" is binary switch: border="1" means with borders; border="" means without borders. There are no other options.

The rest of the table is formed using <tr>, <th>, and <td> tags. <tr> stands for table row, and will hold the cell elements of the table. <th> and <td> are the cell elements, so they will carry the information. Between these two, <th> is reserved for table headers, while <td>, more general, carries the table data.

If you wish, you can also use the elements <thead>, <tbody> and <tfoot> to group them. If you are going to use them, just keep in mind that <thead> does not allow <td> elements in it. You can only use <th> elements in it.

A simple example:

<table border="0" width="480" cellpadding="0" cellspacing="0">
<tr>
<td>column one</td><td>column two</td>
</tr>
<tr>
<td>row two</td><td>last cell</td>
</tr>
</table>

A more complete example:

<table border="1">
<thead>
<tr>
<th>header one</th>
<th>header two</th>
</tr>
</thead>
<tfoot>
<tr>
<td>footer one</td>
<td>footer two</td>
</tr>
</tfoot>
<tbody>
<tr>
<td>data one</td>
<td>data two</td>
</tr>
<tr>
<td>data three</td>
<td>data four</td>
</tr>
</tbody>
</table>

As you may have already noticed, if you use the group tags, the order of the groups becomes less important.

Merging rows and columns

In some occasions you need to merge either two rows or two columns to arrange your data in an appropriate way. If you need to do that, just use the colspan="" or rowspan="" properties to specify how many cells you need to merge, taking into account that colspan="" merges columns and that rowspan="" merges rows. Just use these properties in the cell you need to merge.

<table>
<tr>
<td>column one</td><td>column two</td>
</tr>
<tr>
<td colspan="2">merged cells in a row</td>
</tr>
</table>

Practise, and you will see how easy it is to create tables in HTML.


Learn + Computers and the Internet + Web development