HTML Tutorial / Table Basics: table, tr, th, and td
Use an HTML table for data whose values relate by rows and columns. A table contains rows (tr); each row has header cells (th) or data cells (td). Do not use a table merely to position parts of a page.
The basic table structure
This small table records how many pieces of fruit are in stock. The first row names the columns; the following rows hold values.
<table>
<tr>
<th>Fruit</th>
<th>Stock</th>
</tr>
<tr>
<td>Apples</td>
<td>12 pieces</td>
</tr>
<tr>
<td>Pears</td>
<td>8 pieces</td>
</tr>
</table>
Paste the code into an HTML file's body. Each tr forms one horizontal row, and its cells appear from left to right. The browser's default table style may show little or no border; add borders with CSS only after the data structure is correct. When planning a table, sketch its columns and rows first. To add another fruit, add another data row with a fruit name and stock value.
| Fruit | Stock |
|---|---|
| Apples | 12 pieces |
| Pears | 8 pieces |
Separate header and body rows
Use thead and tbody when you want to group header and data rows explicitly. A summary row can go in tfoot. These elements organize rows; they do not create colors or borders by themselves. You can omit them in a small table, although the browser's HTML parser may insert a tbody into the document tree even when it was not written in the source.
<table>
<thead>
<tr><th>Fruit</th><th>Stock</th></tr>
</thead>
<tbody>
<tr><td>Apples</td><td>12 pieces</td></tr>
<tr><td>Pears</td><td>8 pieces</td></tr>
</tbody>
</table>
Choose header cells and data cells
Use th when a value identifies a row or column; use td for the data associated with that heading. Do not choose th just to make text bold. A table can have both column headers and row headers. Include units, either beside each number or in an appropriate heading. A bare value such as “12” may not tell readers whether it means items or a price.
Once the basics are clear, you can add a caption to name the table, scope to clarify header relationships, and colspan or rowspan when a cell truly covers multiple positions. The MDN table reference describes these features.
Troubleshoot a misaligned table
Check that each ordinary row has the expected number of cells. Mismatched counts can place data under the wrong heading. If a wide table is clipped on a narrow screen, consider a horizontal scrolling area instead of squeezing the content until it is unreadable. Do not insert repeated spaces inside cells to imitate columns; alignment and borders belong in CSS, while the data relationships belong in HTML.










