HTML tables are used to display data in a grid format with rows and columns. While CSS is used to control the visual appearance, HTML provides the semantic structure necessary to define the relationships between cells.
1. The Core Table Elements
A basic table is constructed using four main elements:
| Element | Purpose | Description |
<table> | Container | Defines the start and end of the table. |
<tr> | Table Row | Defines a row in the table. |
<th> | Table Header | Defines a cell containing a header for a column or row. (Content is usually bold and centered.) |
<td> | Table Data | Defines a standard data cell. |
Example: Basic Table
<table>
<tr>
<th>Name</th>
<th>Age</th>
<th>City</th>
</tr>
<tr>
<td>Alice</td>
<td>30</td>
<td>New York</td>
</tr>
<tr>
<td>Bob</td>
<td>24</td>
<td>London</td>
</tr>
</table>
2. Semantic Table Grouping
For better accessibility (especially for screen readers) and structure, HTML uses elements to semantically group the rows of a table into distinct parts:
| Element | Purpose | Description |
<thead> | Table Head | Groups the header content (column titles). |
<tbody> | Table Body | Groups the main, body content (the data rows). |
<tfoot> | Table Foot | Groups summary information (e.g., totals, averages). This is often placed before the <tbody> in the source code but is still displayed at the bottom by the browser. |
<table>
<thead>
<tr>
<th>Product</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<tr>
<td>Keyboard</td>
<td>$75.00</td>
</tr>
<tr>
<td>Mouse</td>
<td>$25.00</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>Total Cost</td>
<td>$100.00</td>
</tr>
</tfoot>
</table>
3. Spanning Rows and Columns
Tables can contain cells that span across multiple rows or multiple columns using the colspan and rowspan attributes.
colspan: Specifies how many columns a cell should stretch across.rowspan: Specifies how many rows a cell should stretch across.
<table>
<thead>
<tr>
<th colspan="2">Employee Details</th>
</tr>
</thead>
<tbody>
<tr>
<td rowspan="2">Alice</td>
<td>Manager</td>
</tr>
<tr>
<td>Full-Time</td>
</tr>
</tbody>
</table>
4. Table Caption
The <caption> element provides a title or summary for the entire table. It is mandatory for accessibility and should be placed immediately after the opening <table> tag.
<table>
<caption>Quarterly Sales Figures (Q1-Q4)</caption>
<thead>
</thead>
<tbody>
</tbody>
</table>
| Element | Status | Correctness |
<caption> | Correct | Placed immediately after <table> and contains the table’s descriptive title. |
| Nesting | Correct | All subsequent elements (<thead>, <tbody>, etc.) are correctly nested within <table>. |
| Overall Structure | Correct | Follows the standard semantic structure of <table> $\rightarrow$ <caption> $\rightarrow$ <thead> $\rightarrow$ <tbody>. |
