Beginner-Friendly Topic
Take your time - it's perfectly normal to re-read this topic 2-3 times. Try the interactive code editor below to run code yourself. Use the Q&A section to check your understanding before moving on.You've got this!
Lesson 4 of 8
Colspan & Rowspan (Merging Cells)
Colspan and rowspan allow you to merge table cells across multiple columns or rows. This is essential for complex table layouts like schedules, spreadsheets, and reports where some cells span multiple columns (like a title row) or multiple rows (like a category label).
How Spanning Works
colspan and rowspan are attributes on <td> or <th> elements:
- colspan="3" - The cell stretches across 3 columns horizontally. You must remove the 2 extra <td> elements from that row since this cell now occupies their space.
- rowspan="2" - The cell stretches across 2 rows vertically. You must remove the corresponding <td> from the NEXT row since this cell now occupies that space.
Common mistakes:
1. Forgetting to remove extra cells - If you add colspan='3' but keep all 3 <td> elements in that row, the table breaks.
2. Miscounting spans - Draw the table on paper first, then count how many cells each span covers.
Use cases:
• Schedule tables (a class spanning 2 hours = rowspan='2')
• Title rows spanning all columns (colspan equal to total columns)
• Merged categories in data reports
Cell merging simplifies complex data layouts while keeping markup clean
Spanning Example
<!DOCTYPE html>
<html>
<head>
<style>
table { border-collapse:collapse; width:100%; max-width:500px; }
th, td { border:1px solid #ddd; padding:10px; text-align:center; }
th { background:#333; color:white; }
.span-header { background:#229c6b; color:white; }
</style>
</head>
<body>
<h2>Class Schedule</h2>
<table>
<tr>
<th colspan="3" class="span-header">Monday Schedule</th>
</tr>
<tr>
<th>Time</th><th>Subject</th><th>Room</th>
</tr>
<tr>
<td>9:00 AM</td>
<td rowspan="2">Mathematics (2 hours)</td>
<td>Room 101</td>
</tr>
<tr>
<td>10:00 AM</td>
<td>Room 101</td>
</tr>
<tr>
<td>11:00 AM</td>
<td>English</td>
<td>Room 205</td>
</tr>
</table>
</body>
</html>Quick Quiz: Spanning
Finished this lesson?