
In HTML, tables are used to display data in rows and columns, similar to a spreadsheet. They are created using the <table>
element and related tags.
1. Basic Table Structure
<table border="1">
<tr>
<th>Name</th>
<th>Age</th>
<th>City</th>
</tr>
<tr>
<td>John</td>
<td>25</td>
<td>New York</td>
</tr>
<tr>
<td>Emma</td>
<td>30</td>
<td>London</td>
</tr>
</table>
2. Main Table Tags
Tag | Purpose |
---|---|
<table> | Defines the table. |
<tr> | Table Row – contains cells. |
<th> | Table Header Cell (bold & centered by default). |
<td> | Table Data Cell. |
3. Table Attributes (Old HTML method)
While CSS is preferred today, HTML still supports:
border
→ Border thickness.cellpadding
→ Space inside each cell.cellspacing
→ Space between cells.
Example:
<table border="1" cellpadding="5" cellspacing="0">
4. Advanced Table Elements
<caption>
→ Table title.
<caption>Student Information</caption>
<thead>
→ Group header rows.<tbody>
→ Group body rows.<tfoot>
→ Group footer rows.
Example:
<table border="1">
<caption>Monthly Sales</caption>
<thead>
<tr>
<th>Month</th>
<th>Sales</th>
</tr>
</thead>
<tbody>
<tr>
<td>January</td>
<td>$1000</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>Total</td>
<td>$1000</td>
</tr>
</tfoot>
</table>
5. Merging Cells
colspan
→ Merge columns.
<td colspan="2">Merged Column</td>
rowspan
→ Merge rows.
<td rowspan="2">Merged Row</td>
6. Styling with CSS (Preferred Method)
<style>
table {
border-collapse: collapse;
width: 50%;
}
th, td {
border: 1px solid black;
padding: 8px;
text-align: center;
}
th {
background-color: lightgray;
}
</style>
7. Example with CSS
<table>
<tr>
<th>Product</th>
<th>Price</th>
</tr>
<tr>
<td>Pen</td>
<td>$2</td>
</tr>
<tr>
<td>Book</td>
<td>$5</td>
</tr>
</table>