Cell spanning
Merge cells with the colspan and rowspan attributes.
Horizontal spanning: colspan
Sometimes a cell needs to cover more than one column. For this you use the colspan attribute. For example <td colspan="2"> says the cell merges two columns.
Picture a table where the first row has a single 'Final' header covering all columns, and below it two separate columns. You cannot build this without colspan. The value is always an integer and tells how many columns are joined.
Vertical spanning: rowspan
When a cell needs to cover more than one row, you use rowspan. For example <td rowspan="3"> says the cell merges three rows downward.
This helps when a single category name on the left must span three rows on the right. It can be combined with colspan in the same cell; but using both at once should be reserved for truly complex layouts.
A merged cell example
A colspan example:
<table>
<tr>
<td colspan="2">Final Term</td>
</tr>
<tr>
<td>Midterm</td>
<td>Final</td>
</tr>
</table>The first row has a single cell covering two columns; the second row has two separate cells. The number of merged columns must match the cell count in the row below.
Exercise Write a table with a merged cell
Add a <table> to body. The first <tr> row should hold a single <td colspan="2"> cell (for example Final Term). The second <tr> row should hold two separate <td> cells (for example Midterm and Final).
Show example solution
<body>
<table>
<tr>
<td colspan="2">Final Term</td>
</tr>
<tr>
<td>Midterm</td>
<td>Final</td>
</tr>
</table>
</body>
Test yourself
-
What does <td colspan="2"> mean?
- The cell's height becomes 2 pixels
- The cell contains two rows
- The cell merges two columns
- The cell is written twice
Show answer
The cell merges two columns — Correct. colspan="2" means the cell merges two columns.
-
Close the merged cell
<table> <tr> <td colspan="2">Final Term____ </tr> <tr> <td>Midterm</td> <td>Final</td> </tr> </table>Show answer
<table> <tr> <td colspan="2">Final Term</td> </tr> <tr> <td>Midterm</td> <td>Final</td> </tr> </table> -
Match each attribute to its meaning
- colspan="2"
- Merges two columns
- rowspan="2"
- Merges two rows
- scope="col"
- Marks a column header
- scope="row"
- Marks a row header