Tables in HTML
Grouping columns
The columns of a table that are somehow related can be grouped together with the colgroup
element. It's important for column groups to have a semantic meaning and not be just a stylistic association. For example, colgroup
can be used to group columns together if they refer to the same product or if they represent the same magnitude, but it shouldn't be used just to make them have the same look (that's what col
is for).
The colgroup
element, alone or conforming a block, must be declared at the begining of the table
, after its opening tag and its caption
, if present. Each colgroup
element declared in this block will define a group with the help of the span
attribute, which will indicate the number of columns that will belong to this group.
Columns grups are declared from left to right, so that the first group will hold the first column in the table plus a number of consecutive columns as speciefied by its span
attribute. The rest of the groups will begin with the first columns at the right of the previous group. This concept could be a little hard to understand, so let's see an example.
The following table has five columns: the first with header cells, the following two with Mike's performance and the last two with Tara's performance. The colgroup
elements declared at the begining reflect the same structure explained before: one colgroup
for the header cells, one for Mike's performance and another one for Tara's performance. Note how the span
attribute indicates the columns spanned by each group, exept for the first that has only one column (the default value for span
). Just to make it visible, we added some style attributes in the column groups.
A couple of things to consider in the next example: first, the default value for the span
attribute is 1, reason why we won't specify it in the first group; and second, the closing tag is opcional for the colgroup
element.
<table class="default">
<colgroup>
<colgroup span="2" style="background: rgba(128, 255, 0, 0.3); border: 1px solid rgba(100, 200, 0, 0.3);">
<colgroup span="2" style="background: rgba(255, 128, 0, 0.3); border: 1px solid rgba(200, 100, 0, 0.3);">
<tr>
<th></th>
<th colspan="2">Mike</th>
<th colspan="2">Tara</th>
</tr>
<tr>
<th></th>
<th>First test</th>
<th>Second test</th>
<th>First test</th>
<th>Second test</th>
</tr>
<tr>
<th>Day 1</th>
<td>25 km</td>
<td>38 km</td>
<td>28 km</td>
<td>37 km</td>
</tr>
<tr>
<th>Day 2</th>
<td>22 km</td>
<td>35 km</td>
<td>30 km</td>
<td>35 km</td>
</tr>
</table>
Mike | Tara | |||
---|---|---|---|---|
First test | Second test | First test | Second test | |
Day 1 | 25 km | 38 km | 28 km | 37 km |
Day 2 | 22 km | 35 km | 30 km | 35 km |
But span
isn't the only way to state the number of columns affected by a group. Sometimes, the col
element can be a better alternative. If you want to investigate further about the subject take a look at the col
element reference.