HTML tables allow web developers to arrange data into rows and columns of
cells. Tables are defined with the <table> tag, with
table rows defined by <tr>, table headers by
<th>, and table data by <td>.
Basic Table Structure
<table>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
</tr>
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
</table>
Table Elements
| Element | Description |
|---|---|
| <table> | Defines a table |
| <tr> | Defines a table row |
| <th> | Defines a table header cell |
| <td> | Defines a table data cell |
| <thead> | Groups header content |
| <tbody> | Groups body content |
| <tfoot> | Groups footer content |
Table with Thead, Tbody, and Tfoot
<table>
<thead>
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
</thead>
<tbody>
<tr>
<td>January</td>
<td>$100</td>
</tr>
<tr>
<td>February</td>
<td>$80</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>Total</td>
<td>$180</td>
</tr>
</tfoot>
</table>
Colspan and Rowspan
Colspan
Make a cell span multiple columns:
<table>
<tr>
<th>Name</th>
<th colspan="2">Phone</th>
</tr>
<tr>
<td>Bill Gates</td>
<td>555-7788</td>
<td>555-7789</td>
</tr>
</table>
Rowspan
Make a cell span multiple rows:
<table>
<tr>
<th>Name</th>
<td>Bill Gates</td>
</tr>
<tr>
<th rowspan="2">Phone</th>
<td>555-7788</td>
</tr>
<tr>
<td>555-7789</td>
</tr>
</table>
Caption Element
Add a caption to your table:
<table>
<caption>Monthly savings</caption>
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
<tr>
<td>January</td>
<td>$100</td>
</tr>
</table>
Best Practices
โ Do:
- Use semantic table elements (thead, tbody, tfoot)
- Add captions for table descriptions
- Use proper headers for accessibility
- Make tables responsive for mobile devices
- Add appropriate padding and spacing
- Use zebra striping for better readability
โ Don't:
- Use tables for page layout
- Nest tables unnecessarily
- Forget to close table tags
- Use complex structures when simple ones suffice
- Ignore mobile responsiveness
- Use tables for data that should be lists