π Mastering the HTML <table> Tag
The <table> element in HTML allows you to display tabular data β rows and columns β in a structured format. This guide walks you through every important tag used inside a table, including real examples and explanations.
π§± Basic Table Structure
Hereβs a simple table:
<table border="1">
<tr>
<th>Day</th>
<th>Subject</th>
</tr>
<tr>
<td>Monday</td>
<td>Math</td>
</tr>
</table>
β Output:
| Day | Subject |
|---|---|
| Monday | Math |
π Key Table Tags Explained
1. <table>
The container tag for all tabular data. It can include optional attributes like:
border: Adds borders to cellscellspacing,cellpadding: Control spacing (CSS preferred today)width: Sets table width
2. <thead>
Groups the header row(s).
<thead>
<tr>
<th>Product</th>
<th>Price</th>
</tr>
</thead>
Use it for accessibility and for sticky headers in CSS.
3. <tbody>
Contains the main body of the table.
<tbody>
<tr>
<td>Apple</td>
<td>$1</td>
</tr>
</tbody>
4. <tfoot>
Defines the footer of a table. Often used for totals.
<tfoot>
<tr>
<td>Total</td>
<td>$3</td>
</tr>
</tfoot>
π Placed before <tbody> in the code but renders after by default.
5. <tr> β Table Row
A container for a single horizontal row of cells.
<tr>
<td>Row 1</td>
<td>Row 2</td>
</tr>
6. <th> β Table Header Cell
Represents a header cell. Bold and centered by default.
<th>Heading</th>
Attributes:
scope="col"(for column headers)scope="row"(for row headers)
7. <td> β Table Data Cell
Represents data in a cell.
<td>Content</td>
You can use:
colspan="2"to merge columnsrowspan="2"to merge rows
βοΈ Full Example
<table border="1" width="100%">
<thead>
<tr>
<th>Student</th>
<th>Subject</th>
<th>Marks</th>
</tr>
</thead>
<tbody>
<tr>
<td>Ravi</td>
<td>Math</td>
<td>90</td>
</tr>
<tr>
<td>Asha</td>
<td>Science</td>
<td>88</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="2">Average</td>
<td>89</td>
</tr>
</tfoot>
</table>
π― Best Practices
- Use
<thead>,<tbody>, and<tfoot>for semantic grouping. - Avoid inline styles β use CSS.
- Add
aria-*orscopefor accessibility. - Use
<caption>for table title (optional):
<caption>Monthly Sales Report</caption>
π‘ Bonus Tips
- You can make tables responsive using CSS:
table {
width: 100%;
border-collapse: collapse;
}
@media (max-width: 600px) {
table,
thead,
tbody,
th,
td,
tr {
display: block;
}
}
- Avoid using tables for layout β use Flexbox or Grid instead.
β Summary
| Tag | Description |
|---|---|
<table> |
Main container |
<thead> |
Header rows |
<tbody> |
Main content rows |
<tfoot> |
Footer rows |
<tr> |
A single table row |
<th> |
Header cell (bold by default) |
<td> |
Standard data cell |
β Youβve Learned
- All major
<table>-related HTML tags - When and how to use them
- Best practices and responsive tricks
Now you're fully equipped to use tables effectively in any web project!