In the previous topic you've practiced creating tables, but they were quite simple and similar. Today you will learn how to merge cells to create tables for a variety of situations when you need to group data.
Two ways to merge cells
You can merge cells in your table both vertically and horizontally. There are two attributes for this:
colspanallows you to merge cells horizontally, the number of cells to be merged is given as a value;rowspanallows you to merge cells vertically, the number of cells to be merged is given as a value.
The value of either attribute has to be a positive integer. It specifies the number of columns or rows that the cell fills.
Here is a standard HTML table that shows types of soup and their prices from the previous topic.
<table border="1">
<tr>
<th>Main dishes</th>
<th>Price</th>
</tr>
<tr>
<td>Tomato soup</td>
<td>$3.95</td>
</tr>
<tr>
<td>French onion soup</td>
<td>$4.49</td>
</tr>
</table>The browser will render it as follows:
We will use this table to demonstrate both colspan and rowspan tags.
Merging cells horizontally
Let's try to merge the cells horizontally:
<table border="1">
<tr>
<th>Main dishes</th>
<th>Price</th>
</tr>
<tr>
<td colspan="2">Tomato soup</td>
<td>$3.95</td>
</tr>
<tr>
<td>French onion soup</td>
<td>$4.49</td>
</tr>
</table>In the above example, one of the cells is shifted to the right.
To correct this situation and make the table more pleasant to look at, you may remove an extra cell:
<table border="1">
<tr>
<th>Main dishes</th>
<th>Price</th>
</tr>
<tr>
<td colspan="2">Tomato soup</td>
</tr>
<tr>
<td>French onion soup</td>
<td>$4.49</td>
</tr>
</table>Merging cells vertically
The rowspan attribute to merge cells vertically is applied the same way:
<table border="1">
<tr>
<th>Main dishes</th>
<th>Price</th>
</tr>
<tr>
<td rowspan="2">Tomato soup</td>
<td>$3.95</td>
</tr>
<tr>
<td>French onion soup</td>
<td>$4.49</td>
</tr>
</table>The cells of the table have shifted, as with colspan. Let's remove an extra cell to make the table better-looking:
<table border="1">
<tr>
<th>Main dishes</th>
<th>Price</th>
</tr>
<tr>
<td rowspan="2">Tomato soup</td>
<td>$3.95</td>
</tr>
<tr>
<td>$4.49</td>
</tr>
</table>So in this topic we've learned how to merge attributes in the tables using colspan and rowspan. Use them when you need to create non-standard tables with one cell for several columns or rows.