The <tbody>
tag in HTML is used to group the main body content (rows) of a table. It helps organize the table into logical sections along with <thead>
and <tfoot>
for headers and footers, respectively.
📌 What Is the <tbody>
Tag?
- The
<tbody>
element wraps one or more<tr>
rows that contain the main data of the table. - It is optional but recommended for better structure and accessibility.
- Enables easier styling and scripting by separating table body from header and footer.
✅ Basic Syntax
<table>
<thead>
<tr>
<th>Item</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<tr>
<td>Pen</td>
<td>$1.20</td>
</tr>
<tr>
<td>Notebook</td>
<td>$2.50</td>
</tr>
</tbody>
</table>
🧪 Example 1: Table with <tbody>
<table border="1">
<thead>
<tr>
<th>City</th>
<th>Population</th>
</tr>
</thead>
<tbody>
<tr>
<td>New York</td>
<td>8,000,000</td>
</tr>
<tr>
<td>London</td>
<td>9,000,000</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="2">Data from 2025 census</td>
</tr>
</tfoot>
</table>
🎨 Why Use <tbody>
?
Benefit | Explanation |
---|---|
Semantic structure | Clarifies table parts for browsers and assistive tech |
Styling control | Allows CSS targeting of the table body |
Scripting convenience | JavaScript can easily select or manipulate body rows |
🎨 Styling <tbody>
You can style the body separately, for example:
tbody tr:nth-child(odd) {
background-color: #f9f9f9;
}
tbody tr:hover {
background-color: #e0e0e0;
}
⚠️ Important Notes
<tbody>
can contain multiple<tr>
elements.- It must be inside a
<table>
. - Browsers often add a
<tbody>
automatically if it is omitted. - Do not place
<thead>
or<tfoot>
inside<tbody>
.
🏁 Summary
The <tbody>
tag is a valuable part of HTML tables that groups the main data rows, making tables more semantic, accessible, and easier to style or script.