Thursday, 7 June 2012

# Use the tbody tag to group multiple tr tags

It is sometimes necessary to group the rows of a HTML table. Say you want to display tabular data of a person and their qualifications, you could achieve this by having the name of the person and qualification on separate rows like this.

Name Qualification
Frank Doe Bachelor of Arts
John Smith Bachelor of Science
John Smith Bachelor of Science
John Smith Master of Science
Alice Mane Diploma of Information Technology
Alice Mane Bachelor of Computer Science

This isn't ideal of course as firstly you are duplicating information, and making the table more busy than it needs to be. But there is also the issue of what to do if there are multiple people with the same name. A nice fix to this issue which is isn't very widely known is that you can group table rows by using the tbody tag. It also comes with the added benefit of being able to create hover styles that span the row and having the collection of rows use the same click event.

Name Qualification
Frank Doe Bachelor of Arts
John Smith Bachelor of Science
John Smith Bachelor of Science
Master of Science
Alice Mane Diploma of Information Technology
Bachelor of Computer Science
<style>
#example {
border:solid #999 1px;
border-collapse:collapse;
}
#example td {
}
#example tbody:hover td {
background:#CCC;
cursor:pointer;
}
</style>

<table id="example">
<tr>
<th>Name</th>
<th>Qualification</th>
</tr>
<tr>
<td>Frank Doe</td>
<td>Bachelor of Arts</td>
</tr>
</tbody>
<tr>
<td>John Smith</td>
<td>Bachelor of Science</td>
</tr>
</tbody>
<tr>
<td rowspan="2">John Smith</td>
<td>Bachelor of Science</td>
</tr>
<tr>
<td>Master of Science</td>
</tr>
</tbody>
</table>