19. Table Cell Merging (Colspan and Rowspan)
The complete logic of joining Columns and Rows together
Real-life analogy
Just as in Excel you select two boxes and press 'Merge Cells', Colspan and Rowspan do the same thing in HTML!
Explanation
2 rules for merging cells together:
colspan="2": Horizontal merge! Joins two or more columns together sideways.rowspan="2": Vertical merge! Joins two or more rows together vertically.- Golden formula: When you put
colspan="2"on a cell, you have to remove one<td>from that same row, otherwise the table will stick out at the edge!
Golden rules
- Always keep the total number of columns consistent.
Common mistake
Not removing the extra td even after adding colspan, which leaves the table disfigured.
Example code
<!DOCTYPE html>
<html>
<head>
<style>
table { width: 100%; border-collapse: collapse; font-family: sans-serif; font-size: 13px; }
th, td { border: 1px solid #cbd5e1; padding: 8px; text-align: left; }
th { background: #0284c7; color: white; }
</style>
</head>
<body style="padding: 10px;">
<table>
<tr>
<th>Name</th>
<th colspan="2">Contact Details (Colspan=2)</th>
</tr>
<tr>
<!-- Rowspan=2: merged 2 rows -->
<td rowspan="2" style="font-weight: bold;">Rahul Kumar</td>
<td>Mobile: 9876543210</td>
<td>Email: rahul@test.com</td>
</tr>
<tr>
<td colspan="2" style="background: #f1f5f9; text-align: center;">Alternate address: New Delhi</td>
</tr>
</table>
</body>
</html>
Quick quiz
Which attribute is used to merge two rows of a table together vertically?
- colspan
- rowspan
- vert-merge
- combine
Show answer
Answer: rowspan
rowspan (Row Span) joins rows together vertically.