How to merge table cells
Short answer
colspan stretches a cell over several columns, rowspan — over several rows:
<style>
table { border-collapse: collapse; }
th, td { border: 1px solid silver; padding: 6px 12px; text-align: center; }
</style>
<table>
<tr><th colspan="2">Schedule</th></tr>
<tr><td rowspan="2">Monday</td><td>Math</td></tr>
<tr><td>Music</td></tr>
<tr><td>Tuesday</td><td>Art</td></tr>
</table>Counting the cells
Every row must add up to the same number of columns. A cell with colspan="2" counts as two. A cell with rowspan="2" also occupies a place in the next row, so that row has one <td> less — like the "Music" row in the example.
A total row
A typical case is a "Total" label spanning all columns except the last:
<style>
table { border-collapse: collapse; }
td { border: 1px solid silver; padding: 6px 12px; }
</style>
<table>
<tr><td>Tea</td><td>2</td><td>$6</td></tr>
<tr><td>Coffee</td><td>1</td><td>$5</td></tr>
<tr><td colspan="2"><b>Total</b></td><td><b>$11</b></td></tr>
</table>Common mistake
rowspan is set, but the cell in the next row is not removed. The extra <td> is pushed out past the table, and a "ragged" column appears on the right:
<style>
td { border: 1px solid silver; padding: 6px 12px; }
</style>
<table>
<tr><td rowspan="2">Monday</td><td>Math</td></tr>
<tr><td>Extra</td><td>Music</td></tr>
</table>Functions used in this recipe
- <td>, <th> — Table cells: `<td>` holds data, `<th>` is a header cell.
- <table> — A table made of rows (`<tr>`) and cells.
- border-collapse — Whether the borders of table cells are separate or merged into single lines.