Dave Woods - Freelance Web Design Warwickshire

Using Tables to display tabular data

Within the Use HTML the right way post last week, I explained that it’s OK to use tables when you’re dealing with tabular data.

I’d therefore like to explain how to markup tables properly so that they can also be accessible.

The Basic table

Displaying a simple table is pretty straight forward.
<table>
<tr>
<td>Name</td>
<td>Age</td>
</tr>
<tr>
<td>Bob</td>
<td>23</td>
</tr>
<tr>
<td>John</td>
<td>37</td>
</tr>
</table>

The code above displays a table of three rows and two columns.

You’ll need to make sure that the same amount of td’s are displayed in each row or ensure that colspan is used on the td to merge the cells.

Adding Meaning

What we’ve covered so far should be pretty straight forward but how can you add extra meaning to the table so that it’s obvious what the headings relate to? This can obviously be applied through styles to make this clearer visually but for anyone browsing without the benefit of CSS, this can still be achieved very easily.
<table summary="table to display people and their ages">
<thead>
<tr>
<th scope="col">Name</th>
<th scope="col">Age</th>
</tr>
</thead>
<tbody>
<tr>
<td>Bob</td>
<td>23</td>
</tr>
<tr>
<td>John</td>
<td>37</td>
</tr>
</tbody>
</table>

A table summary should be used within the <table> tag to explain what the table is displaying.

The row that is used as the heading should be wrapped within <thead> tags and then each of the <td>’s should be changed to <th>’s ensuring that the closing tag is also changed.

Within the <th> tags a new attribute is added called the scope. This is used to describe whether this heading is for the columns (col) or rows (row).

Once the head of your table is in place the rest of the table should be surrounded by <tbody> tags.

Using CSS to style the table

Once the structure of your table is in place it should be easy enough to style the table through CSS. The most common mistakes when styling a table is to apply border, cellpadding and cellspacing to the table. Not only is this invalid when a strict doctype is used, it’s also unnecessary as exactly the same styling can be applied using CSS.

Try using the HTML above along with the following CSS and feel free to modify it to style your own tables.
* {
padding: 0px;
margin: 0px;
}
html {
min-height: 100.1%;
}
body {
font-family: verdana, arial, helvetica, sans-serif;
font-size: 80%;
}
table {
width: 200px;
border-collapse: collapse;
margin: 20px;
}
th {
background-color: #CCC;
color: #000CC;
}
td, th {
border: solid 1px #000;
padding: 2px 5px;
}