Sub topic 5
Grouping rows with thead, tbody, and tfoot
This chapter assumes you can write a basic table with table, tr, td, and th, and that you know how caption names a table. You should also know basic CSS selectors. Here you learn how to split a table's rows into a header section, one or more body sections, and a footer section.
What row groups are
A row group is an element that wraps a set of tr elements and tells the browser what role those rows play. HTML defines three of them:
theadholds the rows that label the columns.tbodyholds the rows of main data.tfootholds summary rows, such as totals.
Without row groups, a table still works. The browser quietly inserts a tbody around any loose tr elements it finds directly inside table. Writing the groups yourself makes that structure explicit, and it gives you three benefits:
- Assistive technology and other software can tell header rows from data rows.
- CSS can target a whole section with one selector.
- Print and scripting tools can treat the sections separately. For example, a script can sort only the
tbodyrows.
A complete example
This table uses all three groups, plus a caption and scope attributes on the header cells.
<table>
<caption>Monthly expenses</caption>
<thead>
<tr>
<th scope="col">Item</th>
<th scope="col">Cost</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">Rent</th>
<td>900</td>
</tr>
<tr>
<th scope="row">Food</th>
<td>300</td>
</tr>
</tbody>
<tfoot>
<tr>
<th scope="row">Total</th>
<td>1200</td>
</tr>
</tfoot>
</table>The thead row labels the two columns. The tbody rows hold the data. The tfoot row holds the total. Each row group contains only tr elements. Cells such as td and th go inside those rows, never directly inside the group.
Where each element goes
A table's children follow a fixed order. The diagram shows which elements may appear directly inside table and how rows and cells nest below them.
In the current HTML specification, the content model of table is, in this order:
- An optional
caption. - Zero or more
colgroupelements. - An optional
thead. - Either zero or more
tbodyelements, or one or moretrelements. - An optional
tfoot.
The practical rule is to write caption, then any colgroup, then thead, then tbody, then tfoot. That is the order a reader sees on screen and the order that works in every browser.
thead: the header section
thead wraps the rows that describe the columns. It usually has one tr made of th cells, though it can have several rows. A table has at most one thead.
<table>
<caption>Quarterly sales</caption>
<thead>
<tr>
<th scope="col">Region</th>
<th scope="col">Q1</th>
<th scope="col">Q2</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">North</th>
<td>120</td>
<td>135</td>
</tr>
</tbody>
</table>Putting th cells in a thead does not by itself tell assistive technology which direction they label. Keep the scope="col" attribute on them. The next chapters cover scope in detail.
A thead row may contain td cells as well as th cells. A common case is an empty top-left corner cell in a table that has both column and row headers. An empty td there is correct, because the cell labels nothing.
tbody: the data sections
tbody holds the main rows. A table may have several tbody elements, and this is one of the most useful and least known features of row groups. Each tbody marks a distinct block of data, such as a category, a day, or a department.
<table>
<caption>Fruit and vegetable stock</caption>
<thead>
<tr>
<th scope="col">Item</th>
<th scope="col">Units</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">Apples</th>
<td>40</td>
</tr>
<tr>
<th scope="row">Pears</th>
<td>25</td>
</tr>
</tbody>
<tbody>
<tr>
<th scope="row">Carrots</th>
<td>60</td>
</tr>
<tr>
<th scope="row">Onions</th>
<td>35</td>
</tr>
</tbody>
</table>Multiple tbody elements give you a place to attach a visual break between blocks. For example, this rule draws a thicker line above every body section after the first:
tbody + tbody {
border-top: 3px solid #333;
}For this rule to show up, the table needs border-collapse: collapse, because a border on a tbody is only drawn in the collapsed-border model. Styling is covered in a later chapter.
The implied tbody
If you write tr elements directly inside table, the HTML parser wraps them in a tbody for you. You cannot see this in the source, but you can see it in the DOM. This has one consequence that catches people out. The child combinator in CSS and in querySelector does not match the way the source suggests.
<table id="plain">
<tr><td>One</td></tr>
<tr><td>Two</td></tr>
</table>
<script>
const table = document.getElementById("plain");
console.log(table.querySelectorAll(":scope > tr").length);
console.log(table.querySelectorAll(":scope > tbody > tr").length);
</script>The first count is 0 and the second is 2. The rows are children of an automatically created tbody, not of table. Writing the tbody yourself removes the surprise, and it makes the source match the DOM.
Omitting end tags
HTML lets you leave out some end tags. You may omit </tbody> when the next element is another tbody or a tfoot, or when the parent ends. You may also omit </tr>, </td>, and </th> in similar cases. This is valid HTML, but it makes tables harder to read and edit. This tutorial always writes the end tags.
tfoot: the summary section
tfoot holds rows that summarize or close the table. Totals, averages, and notes about the data are typical uses. A table has at most one tfoot.
<table>
<caption>Team hours this week</caption>
<thead>
<tr>
<th scope="col">Person</th>
<th scope="col">Hours</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">Ana</th>
<td>38</td>
</tr>
<tr>
<th scope="row">Ben</th>
<td>41</td>
</tr>
</tbody>
<tfoot>
<tr>
<th scope="row">Total</th>
<td>79</td>
</tr>
</tfoot>
</table>The footer row starts with a th that has scope="row", so the label "Total" is the header for its row. A footer is not limited to numbers. You can use it for a source note by spanning one cell across all columns with colspan, which the next chapter covers.
How the groups behave in a browser
Browsers apply a few rules to row groups, and knowing them prevents surprises.
| Behavior | Details |
|---|---|
| Display order | `thead` is drawn first and `tfoot` last, whatever order they appear in the source |
| Default styling | Browsers add no visible style to the groups themselves. Header `th` cells are bold and centered by the default stylesheet |
| Number allowed | One `thead`, one `tfoot`, and any number of `tbody` elements |
| Column widths | All groups share the same columns, so widths are calculated across the whole table |
| Printing | Browsers may repeat `thead` and `tfoot` on each printed page when a table spans several pages |
The last point is helpful. If a long table prints on three pages, the column labels in the thead can appear at the top of every page. Without thead, the labels appear only once.
Styling the groups
Because each group is an element, a CSS rule can target it. The rules below shade the header, set the footer in bold with a top border, and keep the numbers in the body aligned to the right.
table {
border-collapse: collapse;
}
thead th {
background: #f0f0f0;
}
tbody td {
text-align: right;
}
tfoot {
font-weight: bold;
border-top: 2px solid #333;
}The thead th selector matches only header cells inside the header section. A th inside tbody, such as a row header, is not matched, so it keeps its default look.
Common mistakes
These errors appear often in real tables.
- Mixing loose rows and groups. If a table has a
theadand also hastrelements directly insidetable, the markup is invalid. Put every row in a group once you use any group. - Placing cells outside rows. A
tdorthmust sit inside atr. Atddirectly insidetbodyis invalid, and the parser will move or wrap it in unexpected ways. - Using more than one
theadortfoot. The specification allows only one of each. For repeated headers inside the data, use athrow inside atbody, or use severaltbodyelements. - Putting the total in
tbody. A total row in the body is not wrong for display, but software cannot tell it from data. When you sort the body rows with a script, the total moves with them. Atfootstays put. - Using groups for layout. Row groups describe the role of rows. They are not a layout tool, and a table used for page layout is a different problem covered in the first chapter.
- Treating
theadas a replacement forth. Atheadwrapper does not make its cells headers. Usethfor header cells andscopeto state their direction.
Sorting a table body safely
A good reason to use row groups is that scripts can work on one group and leave the others alone. This small script sorts the body rows of a table by the number in the second column. The header and footer are untouched.
<table id="hours">
<caption>Team hours this week</caption>
<thead>
<tr>
<th scope="col">Person</th>
<th scope="col">Hours</th>
</tr>
</thead>
<tbody>
<tr><th scope="row">Ana</th><td>38</td></tr>
<tr><th scope="row">Ben</th><td>41</td></tr>
<tr><th scope="row">Cy</th><td>35</td></tr>
</tbody>
<tfoot>
<tr><th scope="row">Total</th><td>114</td></tr>
</tfoot>
</table>
<script>
const body = document.querySelector("#hours tbody");
const rows = Array.from(body.rows);
rows.sort((a, b) => {
return Number(b.cells[1].textContent) - Number(a.cells[1].textContent);
});
rows.forEach((row) => body.appendChild(row));
</script>The script reads body.rows, which contains only the rows of that tbody. After it runs, the order is Ben, Ana, Cy, and the thead and tfoot rows have not moved. If the total row were in the tbody, it would be sorted in with the people.
Check your understanding
Exercise
A table has a header row, six data rows, and a final row with the total. The author wrote all eight rows directly inside table with no row groups. Name two problems this causes, and describe the fix.
Show answer
First, software cannot tell the header and total rows from data rows, so a script that sorts rows will move the header and total with the rest, and CSS cannot target them as sections. Second, the parser wraps the loose rows in an implied tbody, so selectors like table > tr no longer match the DOM. The fix is to put the header row in thead, the six data rows in tbody, and the total row in tfoot, with every tr inside one of the groups.
Exercise
You want a thick line between two blocks of data, "Fruit" and "Vegetables", in one table. How should you mark up the blocks, and which CSS rule draws the line?
Show answer
Put each block in its own tbody. Set border-collapse: collapse on the table, then use tbody + tbody { border-top: 3px solid #333; } to draw a thick line above every tbody that follows another tbody.
Exercise
Is this table valid? Explain why or why not. <table><thead><tr><th>A</th></tr></thead><tr><td>1</td></tr></table>
Show answer
It is not valid. Once a table uses a thead, every other row must also sit inside a row group. The row with 1 is a loose tr directly inside table, which is not allowed beside a thead. Wrap it in a tbody.