To merge cells vertically in an HTML table, you use the rowspan
attribute within the <td>
(table data) or <th>
(table header) tag.
Merging Cells Vertically with rowspan
As stated in the reference, "We use the colspan and rowspan attribute, to merge cells in HTML." Specifically, "The rowspan attribute is for the number of rows a cell should merge, whereas the colspan attribute is for the number of columns a cell should merge."
To merge cells vertically, you will use the rowspan
attribute. This attribute tells a cell to span across a specified number of rows, effectively merging it with the cells below it in the same column. The attribute "should be placed inside the <td tag" (or <th>
tag if you are merging header cells).
Here's how it works:
- Identify the cell where you want the vertical merge to start.
- Add the
rowspan
attribute to that cell's<td>
or<th>
tag. - Set the value of
rowspan
to the total number of rows you want the cell to span (including the starting row). - In the subsequent rows that the cell spans over, omit the corresponding
<td>
or<th>
tags in that column. HTML will automatically handle the layout based on therowspan
definition in the row above.
Example: Merging Table Cells Vertically
Let's look at a simple example where we merge two cells vertically in the second column of a table.
<table>
<thead>
<tr>
<th>Header 1</th>
<th>Header 2</th>
<th>Header 3</th>
</tr>
</thead>
<tbody>
<tr>
<td>Row 1, Cell 1</td>
<td rowspan="2">Row 1 & 2, Cell 2 (Merged)</td>
<td>Row 1, Cell 3</td>
</tr>
<tr>
<td>Row 2, Cell 1</td>
<!-- The cell for Row 2, Cell 2 is omitted because the one above spans into this row -->
<td>Row 2, Cell 3</td>
</tr>
<tr>
<td>Row 3, Cell 1</td>
<td>Row 3, Cell 2</td>
<td>Row 3, Cell 3</td>
</tr>
</tbody>
</table>
Explanation of the Example
- In the
<thead>
, we have three header cells. - In the first row of the
<tbody>
(<tr>
):- The second
<td>
hasrowspan="2"
. This tells the browser that this cell should extend down and occupy the space of two rows (its own row plus the next row).
- The second
- In the second row of the
<tbody>
(<tr>
):- We only have two
<td>
elements: "Row 2, Cell 1" and "Row 2, Cell 3". - The space where "Row 2, Cell 2" would normally be is left empty in the HTML markup for this row. The cell from the row above (
<td rowspan="2">
) automatically fills this vertical space.
- We only have two
- The third row (
<tr>
) is a standard row with three cells.
This results in the cell containing "Row 1 & 2, Cell 2 (Merged)" spanning across the first two body rows vertically in the second column.
Using the rowspan
attribute is the standard and correct method in HTML for merging cells vertically within table structures, providing flexibility for complex layouts and data presentations.