XHTML & CSS Tutorial - Tables

Tables are used to display tabular data. Some sites use tables as a layout for there entire webpage. This of course is wrong and these people are missing out on a thing called CSS. Compared to the XHTML you've learnt so far tables is the most complex. I'll start by showing you a simple 2 by 2 table

<table border="1">
<tr>
<td>Row 1 Column 1</td>
<td>Row 1 Column 2</td>
</tr>
<tr>
<td>Row 2 Column 1</td>
<td>Row 2 Column 2</td>
</tr>
</table>

Row 1 Column 1 Row 1 Column 2
Row 2 Column 1 Row 2 Column 2

  • <table border="1"> is the opening tag for the table, as you would of guessed. The border="1" makes a border width of 1.
  • <tr> starts a new table row
  • <td> is the tag for table data. They must be between <tr> tags. This is where all the data of your table will go.

Thats all great but what about if you wanted to say whats being displayed in each column? Thats where the table header tag (<th>) comes in.

<table border="1">
<tr>
<th>Name</th>
<th>Age</th>
</tr>
<tr>
<td>Bob</td>
<td>45</td>
</tr>
<tr>
<td>Joe</td>
<td>26</td>
</tr>
</table>

Name Age
Bob 45
Joe 26

Remember tables work in rows so you need to code rows at a time. Colspan and rowspan lets you increase the size of a column and row. Let me show you what I'm talking about.

<table border="1">
<tr>
<th colspan="4">Random Data</th>
</tr>
<tr>
<th>Name</th>
<th>Age</th>
<th>Food</th>
<th>Location</th>
</tr>
<tr>
<td>Bob</td>
<td>45</td>
<td>Eggs</td>
<td>UK</td>
</tr>
<tr>
<td>Joe</td>
<td>26</td>
<td>Chips</td>
<td>USA</td>
</tr>
</table>

Random Data
Name Age Food Location
Bob 45 Eggs UK
Joe 26 Chips USA

As you can see the table header has spanned across 4 columns. Rowspan does the same but for rows. As you can see from the example below when using rowspan you include it in the first <tr> tags with the rest of the first row. Where as colspan has its own row.

<table border="1">
<tr>
<th rowspan="3">Random Data</th>
<th>Name</th>
<th>Age</th>
<th>Food</th>
<th>Location</th>
</tr>
<tr>
<td>Bob</td>
<td>45</td>
<td>Eggs</td>
<td>UK</td>
</tr>
<tr>
<td>Joe</td>
<td>26</td>
<td>Chips</td>
<td>USA</td>
</tr>
</table>

Random Data Name Age Food Location
Bob 45 Eggs UK
Joe 26 Chips USA

Previous - 9. Lists || Next - 11. Forms