How to Use the colgroup Element
The colgroup element groups columns in a table. For example, you can group the “Basic” and “Plus” plan columns together.
The short answer
Put colgroup inside a table, after its caption and before the heading and data rows.
colgroup does not name a column. Use th for a visible heading. If you do not need to group columns or style them together, you can leave colgroup out.
A small example
<style>
.plan-columns {
background-color: #eaf3ff;
}
</style>
<table>
<caption>Monthly plan prices</caption>
<colgroup>
<col>
</colgroup>
<colgroup span="2" class="plan-columns"></colgroup>
<thead>
<tr>
<th scope="col">Item</th>
<th scope="col">Basic</th>
<th scope="col">Plus</th>
</tr>
</thead>
<tbody>
<tr><th scope="row">Monthly price</th><td>$5</td><td>$9</td></tr>
</tbody>
</table>
| Item | Basic | Plus |
|---|---|---|
| Monthly price | $5 | $9 |
The first column is represented by col. The other two are grouped with span="2". CSS adds the blue background; the th elements provide the column headings.
How colgroup and col work together
colgroupmakes a group of columns.colrepresents one or more columns inside that group.- If the group has no child
colelements, you can usespanoncolgroupto set the number of columns. - To describe columns one by one, put
colelements insidecolgroupand usespanon eachcolas needed.
Choose one method. Do not combine a span on colgroup with child col elements.
Column headings are separate
colgroup groups columns, but it does not give them names such as “Price” or “Name.” Write column headings with th scope="col". A heading that describes a whole column group still needs to be written in a th cell.
Common mistakes
- Putting a heading's text in
colgroup. Usethto show and name a heading. - Putting
colgroupaftertbodyortr. Column groups go before the rows. - Using both
colgroup span="2"and childcolelements. Pick one way to describe the columns. - Expecting every CSS setting to work on a column. Only a limited set applies. If a background color is hidden, check whether a cell or row has its own background.
Related pages
- For individual columns, see How to Use the col Element.
- For the whole table, see the table element.
- For column headings, see thead and th.
- For detailed rules and browser or accessibility observations, see colgroup in Atlas and col in Atlas.