Merging Cells in HTML
When designing tables in HTML, you might encounter situations where you need to merge two or more cells into one to display content clearly. This process is called cell merging, and it's done using the <colspan>
and <rowspan>
attributes of the <td>
or <th>
elements.
1. Merging Columns with colspan
The <colspan>
attribute is used when you want a cell to span across multiple columns. For instance, if you're creating a table with a header that spans two columns, you can use<colspan>
.
<table border="1">
<tr>
<th colspan="2">Merged Header</th>
</tr>
<tr>
<td>Column 1</td>
<td>Column 2</td>
</tr>
</table>
Result:
The first row will have a single cell that spans two columns.
2. Merging Rows with rowspan
The <rowspan>
attribute is used to make a cell span multiple rows. For example, you might want to merge cells in the first column of two rows.
<table border="1">
<tr>
<td rowspan="2">Merged Row</td>
<td>Row 1, Column 2</td>
</tr>
<tr>
<td>Row 2, Column 2</td>
</tr>
</table>
Result:
The first cell in the first column will span two rows.
3. Combining colspan and rowspan
You can even combine both <colspan>
and<rowspan>
to create more complex layouts.
<table border="1">
<tr>
<th rowspan="2" colspan="2">Merged Cell</th>
<td>Column 3</td>
</tr>
<tr>
<td>Column 3, Row 2</td>
</tr>
</table>
Result:
The first cell spans two rows and two columns.
4. Why Merge Cells?
Merging cells is helpful when:
- Creating headers that span multiple sections of a table.
- Simplifying table layouts for better readability.
- Designing reports, schedules, or invoices.
By mastering colspan and rowspan, you can build professional and visually appealing tables in HTML.