HTML Tables
Tables in HTML are super useful when you need to organize information in rows and columns, like pricing charts, schedules, or comparisons.
Letβs break it down step-by-step with practical examples.
π Basic Table Structure
HTML tables are made up of:
<table>
β wraps the entire table<tr>
β table row<th>
β table header (bold + centered by default)<td>
β table data (regular cell)
β Example:
<table>
<tr>
<th>Course</th>
<th>Duration</th>
</tr>
<tr>
<td>HTML</td>
<td>2 Weeks</td>
</tr>
<tr>
<td>CSS</td>
<td>3 Weeks</td>
</tr>
</table>
π§ Table headers automatically make the content bold and centered.
π rowspan & colspan β Merging Cells
πΌ rowspan
β Merge rows vertically
<td rowspan="2">Frontend</td>
π½ colspan
β Merge columns horizontally
<th colspan="2">Course Details</th>
π§ͺ Example with Both:
<table border="1">
<tr>
<th rowspan="2">Course</th>
<th colspan="2">Duration</th>
</tr>
<tr>
<td>Weeks</td>
<td>Hours</td>
</tr>
<tr>
<td>HTML</td>
<td>2</td>
<td>20</td>
</tr>
</table>
π§ Table Head, Body, and Foot
HTML5 supports semantic grouping:
<thead>
: table header rows<tbody>
: main content rows<tfoot>
: footer row(s)
β Example:
<table border="1">
<thead>
<tr>
<th>Item</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<tr>
<td>Pen</td>
<td>$1</td>
</tr>
<tr>
<td>Notebook</td>
<td>$2</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>Total</td>
<td>$3</td>
</tr>
</tfoot>
</table>
π§ Bonus: <thead>
, <tbody>
, and <tfoot>
are useful for screen readers and JavaScript sorting plugins.
π¨ Basic Table Styling (Inline or CSS)
You can style tables inline or via CSS.
Inline example:
<table border="1" style="border-collapse: collapse; width: 100%;">
<tr style="background-color: #f0f0f0;">
<th>Name</th>
<th>Email</th>
</tr>
<tr>
<td>John</td>
<td>john@example.com</td>
</tr>
</table>
CSS version:
table {
border-collapse: collapse;
width: 100%;
}
th, td {
border: 1px solid #ccc;
padding: 8px;
}
th {
background-color: #f9f9f9;
text-align: left;
}
β Summary Table
Tag | Purpose |
---|---|
<table> | Main table wrapper |
<tr> | Table row |
<th> | Header cell |
<td> | Data cell |
rowspan | Merge cells vertically |
colspan | Merge cells horizontally |
<thead> / <tbody> / <tfoot> | Grouping sections for structure and accessibility |
π§ͺ Practice It Yourself
<table border="1">
<thead>
<tr>
<th>Subject</th>
<th>Marks</th>
</tr>
</thead>
<tbody>
<tr>
<td>Math</td>
<td>95</td>
</tr>
<tr>
<td>Science</td>
<td>90</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>Total</td>
<td>185</td>
</tr>
</tfoot>
</table>
π Coming Up Next:
Letβs learn how to collect user data with HTML Forms.
π Next: HTML Forms