Sometimes we want cells to span multiple rows or columns. Take the following simple example, which shows the names of common animals. In some cases, we want to show the names of the males and females next to the animal name. Sometimes we don't, and in such cases we just want the animal name to span the whole table.
The initial markup looks like this:
<table>
<tr>
<th>Animals</th>
</tr>
<tr>
<th>Hippopotamus</th>
</tr>
<tr>
<th>Horse</th>
<td>Mare</td>
</tr>
<tr>
<td>Stallion</td>
</tr>
<tr>
<th>Crocodile</th>
</tr>
<tr>
<th>Chicken</th>
<td>Hen</td>
</tr>
<tr>
<td>Rooster</td>
</tr>
</table>
table {
border-collapse: collapse;
}
td,
th {
border: 1px solid black;
padding: 10px 20px;
}
But the output doesn't give us quite what we want:
We need a way to get "Animals", "Hippopotamus", and "Crocodile" to span across two columns, and "Horse" and "Chicken" to span downwards over two rows. Fortunately, table headers and cells have the colspan
and rowspan
attributes, which allow us to do just those things. Both accept a unitless number value, which equals the number of rows or columns you want spanned. For example, colspan="2"
makes a cell span two columns.
Let's use colspan
and rowspan
to improve this table.
- First, make a local copy of our animals-table.html and minimal-table.css files in a new directory on your local machine. The HTML contains the same animals example as you saw above.
- Next, use
colspan
to make "Animals", "Hippopotamus", and "Crocodile" span across two columns.
- Finally, use
rowspan
to make "Horse" and "Chicken" span across two rows.
- Save and open your code in a browser to see the improvement.