Topic 30 of 41
Colspan & Rowspan
Overview
Sometimes data in a table doesn't fit perfectly into a 1x1 grid. Imagine an Excel spreadsheet where you want a title to stretch across the top of 4 different columns, or a category name to stretch vertically down across 3 rows.
In Excel, this is called 'Merge Cells'. In HTML, we use the `colspan` (column span) and `rowspan` (row span) attributes.
Syntax
Using `colspan="2"` tells a `<td>` or `<th>` to stretch horizontally and take up the space of 2 columns.
Colspan (Horizontal Merging)
html
<table border="1">
<tr>
<!-- This header stretches across TWO columns -->
<th colspan="2">Student Details</th>
</tr>
<tr>
<!-- Since the top row has 2 columns of space,
this row provides the 2 individual columns -->
<td>Kartik</td>
<td>Computer Science</td>
</tr>
</table>Using `rowspan="3"` tells a cell to stretch vertically downwards, pushing into the space of the rows below it. You have to be careful here, because the rows below will now need one LESS cell!
Rowspan (Vertical Merging)
html
<table border="1">
<tr>
<!-- Stretches DOWN into the next row -->
<th rowspan="2">Sciences</th>
<td>Physics</td>
</tr>
<tr>
<!-- This row only needs ONE td, because the 'Sciences'
header is occupying the left side of this row! -->
<td>Chemistry</td>
</tr>
</table>Common Pitfalls
- Rowspan and Colspan can easily break your table layout. If a table is supposed to have 4 columns, and you add a colspan='3', you must only provide 1 more cell in that row. If you provide more, the table will physically break out of its boundaries.
Real-World Example
A complex invoice table merging columns for the total price:
example
html
<table border="1" width="100%">
<tr>
<th>Item</th>
<th>Quantity</th>
<th>Price</th>
</tr>
<tr>
<td>Mechanical Keyboard</td>
<td>1</td>
<td>$100</td>
</tr>
<tr>
<td>Wireless Mouse</td>
<td>2</td>
<td>$50</td>
</tr>
<!-- Footer row merging cells -->
<tr>
<!-- Stretches across Item and Quantity columns -->
<th colspan="2" style="text-align: right;">Total Amount:</th>
<td>$200</td>
</tr>
</table>