Example usage of <tbody>

Every now and then I poke around on the w3.org website eyeballing the HTML / XHTML specs to see if I'm doing things correct. One of the things I've been bumping into was the fact that I needed to group some table rows (<TR>) together, but if you give table rows a :hover effect, it'll only kick off the hover on one row at a time. I  need the group of table rows to hover all at the same time.

So, I went back to the w3 site and read the table spec. One of the things I noticed was the fact that I hadn't really been paying attention to the fact that <table> tags had a <thead>, <tfoot> & <tbody>. Also, from the example given, you can have multiple <tbody>s which would solve my problem of grouping table rows together. I could put the :hover affect on a <tbody> spanning 3 rows and all three rows would trigger :hover as if I moused over 1 row.

Example code:
<style>
table tbody:hover { background-color: pink; }
</style>

<table border="1" cellspacing="0" cellpadding="0">
<tbody>
    <tr><td>Row 1 - Tbody 1</td></tr>
    <tr><td>Row 2 - Tbody 1</td></tr>
    <tr><td>Row 3 - Tbody 1</td></tr>
</tbody>
<tbody>
    <tr><td>Row 1 - Tbody 2</td></tr>
    <tr><td>Row 2 - Tbody 2</td></tr>
    <tr><td>Row 3 - Tbody 2</td></tr>
</tbody>
<tbody>
    <tr><td>Row 1 - Tbody 3</td></tr>
    <tr><td>Row 2 - Tbody 3</td></tr>
    <tr><td>Row 3 - Tbody 3</td></tr>
</tbody>
</table>

And demo:

Row 1 - Tbody 1
Row 2 - Tbody 1
Row 3 - Tbody 1
Row 1 - Tbody 2
Row 2 - Tbody 2
Row 3 - Tbody 2
Row 1 - Tbody 3
Row 2 - Tbody 3
Row 3 - Tbody 3

This is also pretty useful for styling with css and using effects with jQuery.

todd sharp

todd sharp wrote on 05/27/10 3:53 PM

Just curious - have you tested this in multiple browsers? Something tells me I remember some browsers have a hard time with multiple tbody's...
Todd Rafferty

Todd Rafferty wrote on 05/27/10 4:20 PM

If a browser isn't allowing multiple <tbody> then they're not following the basic HTML spec. o_O I know this works on FireFox, Chrome, Safari, IE on a PC. I didn't test Opera, but I'm sure they're on the ball. :)

I can't comment for OSX / Linux.
Kyle

Kyle wrote on 05/28/10 11:59 AM

It works on Opera 10.54, and I'd guess earlier versions too.

Leave a comment


(required field)

(required field)