Sub topic 8
Styling Whole Columns with colgroup and col
What you need first
This chapter assumes you can write a basic table with table, tr, th, and td. It also assumes you know how to group rows with thead and tbody and how to write simple CSS rules with class selectors. Spanning cells with colspan helps, because column groups depend on the same idea of a grid made of columns.
The problem column groups solve
HTML is organized by rows. Every cell is written inside a tr, so the markup has no column element that holds cells. If you want to shade the "Population" column, you could add a class to every td in that column. That works, but it is repetitive and easy to get wrong when you add a row.
The colgroup and col elements describe the columns of the table without containing any cells. You declare them once at the top, and a small set of CSS properties applies to every cell in that column.
Where the elements go
A colgroup is a child of table. It comes after the caption, if there is one, and before any thead, tbody, tfoot, or tr. A colgroup can contain col elements. Each col is a void element, so it has no closing tag and no content.
<table>
<caption>City statistics</caption>
<colgroup>
<col class="name">
<col class="num">
<col class="num">
</colgroup>
<thead>
<tr>
<th scope="col">City</th>
<th scope="col">Population</th>
<th scope="col">Area (km²)</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">Oslo</th>
<td>700000</td>
<td>454</td>
</tr>
<tr>
<th scope="row">Bergen</th>
<td>285000</td>
<td>465</td>
</tr>
</tbody>
</table>The first col matches the first column, the second col matches the second column, and so on. The table has three columns, so there are three col elements.
The diagram shows that colgroup is a sibling of the row groups. Its col children describe columns and never hold cell content.
Covering several columns with span
The span attribute makes one col apply to more than one adjacent column. Its value is a positive whole number, and the default is 1.
<colgroup>
<col>
<col span="2" class="numeric">
</colgroup>This describes three columns. The first has no special style, and the second and third both receive the class numeric. You get the same result by writing two separate col elements with the same class. Use span when the columns really share a purpose.
colgroup also accepts span, but only when it has no col children. In that case the colgroup itself stands in for the columns:
<colgroup span="2" class="labels"></colgroup>If you put col children inside, the span on the colgroup is invalid. Pick one approach per group.
Using several colgroups
You can write more than one colgroup. This is useful when columns form logical sections, such as an identifier column followed by a block of monthly figures. Each colgroup can then take its own border or background, which marks the section as a whole.
<colgroup class="identity">
<col>
</colgroup>
<colgroup class="months">
<col>
<col>
<col>
</colgroup>Keep the count honest. The total number of columns declared across all colgroup and col elements should match the widest row of the table. If you declare fewer, the extra columns simply get no column styles. If you declare more, the table gains empty columns.
Which CSS properties work
This is the most important limit to know. Browsers apply only four properties from a col or colgroup to the cells in that column.
| Property | What it does on a column | Notes |
|---|---|---|
| `background` | Paints behind the column's cells | Cells with their own background cover it |
| `border` | Draws a border around the column | Only applies when `border-collapse: collapse` is set on the table |
| `width` | Sets the column width | Works best with `table-layout: fixed` |
| `visibility` | `collapse` removes the column from the layout | Other values behave like `visible` |
Other properties, such as color, font-weight, text-align, or padding, have no effect when set on a col. Text properties are inherited through the document tree, and cells are not children of a col. They are children of a tr. So a rule like col.numeric { text-align: right; } does nothing.
A working example
Here is a complete page that uses the supported properties: background, width, and a column border.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Column styles</title>
<style>
table {
border-collapse: collapse;
table-layout: fixed;
width: 30rem;
}
th, td {
padding: 0.5rem 0.75rem;
text-align: left;
}
col.name {
width: 12rem;
}
col.num {
width: 9rem;
background: #eef5ff;
}
col.highlight {
border: 2px solid #c0392b;
}
</style>
</head>
<body>
<table>
<caption>City statistics</caption>
<colgroup>
<col class="name">
<col class="num">
<col class="num highlight">
</colgroup>
<thead>
<tr>
<th scope="col">City</th>
<th scope="col">Population</th>
<th scope="col">Area (km²)</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">Oslo</th>
<td>700000</td>
<td>454</td>
</tr>
<tr>
<th scope="row">Bergen</th>
<td>285000</td>
<td>465</td>
</tr>
</tbody>
</table>
</body>
</html>The two numeric columns get a light blue background and a fixed width. The last column also gets a red border around its full height. Without border-collapse: collapse, that border would not appear.
Layering with row backgrounds
A table paints its parts in layers, from back to front: the table, column groups, columns, row groups, rows, and then cells. A later layer covers an earlier one wherever it has an opaque background.
This matters when you combine column shading with row striping. Suppose you write tbody tr:nth-child(even) { background: #fafafa; } as in the styling chapter. The row background is painted over the column background, so the column shading disappears on the striped rows.
You have two ways to handle this:
- Use a semi-transparent color for the row stripe, such as
rgba(0, 0, 0, 0.04), so the column color shows through. - Skip the column background and style the cells directly with a selector like
td:nth-child(2).
Both are valid. Choose the first when you want the column tint to remain visible, and the second when you need full control over how stripes and column colors combine.
Aligning text by column
Since text-align on col is ignored, you need another way to right-align a number column. The usual answer is :nth-child() on the cells:
td:nth-child(n + 2),
th[scope="col"]:nth-child(n + 2) {
text-align: right;
}The selector n + 2 matches the second child and every child after it, so the rule covers all columns except the first. This ties the style to column position. If you reorder the columns later, you must update the selector.
A second option is a class on each cell, such as <td class="num">. It survives reordering, but you must repeat it on every cell.
A newer option uses :has() to read the column class from the table, but it still needs to know positions. For most tables, :nth-child() is the simple choice.
Widths and table-layout
The width property on a col sets a preferred width for that column. How the browser treats it depends on table-layout.
- With
table-layout: auto, which is the default, the browser measures the content of all cells and uses your width as a hint. Long unbreakable text can still make a column wider than you asked. - With
table-layout: fixed, the browser reads widths from thecolelements first, then from the first row's cells, and does not look at the rest of the content. The table renders faster, and your widths are followed. Text that does not fit wraps or overflows, depending on youroverflowandword-breaksettings.
Fixed layout needs a table width that is not auto. If you leave it out, the browser falls back to automatic layout.
Mixing units is fine. You can give one column a fixed 12rem and let the others share the remaining space by leaving their width unset.
Hiding a column
Setting visibility: collapse on a col removes that column and reclaims its space:
col.optional {
visibility: collapse;
}A script or media query can switch the rule on and off, so the column disappears when space is tight. Be careful about accessibility. In browsers that support collapse, the hidden cells are generally not rendered, so the data is not available to anyone. Do not hide a column that carries information readers need.
Spanning cells and column styles
A cell with colspan="2" sits across two columns. The column backgrounds are still painted per column behind it, but the cell's own background, if it has one, covers both. Column borders keep following the column edges, so a border on a single col can appear to run through a spanning cell's area.
Count columns the way the grid counts them, not by looking at the number of td elements in one row. A row with a spanning cell has fewer cells than columns, and your col elements must still match the grid.
Common mistakes
- Putting
colgroupin the wrong place. If it comes aftertheadortbody, the table is invalid, and browsers may handle it inconsistently. Place it right aftercaption. - Writing
</col>. Thecolelement is void and has no end tag. - Using
spanon acolgroupthat hascolchildren. Usespanon thecolelements instead. - Styling text on a
col. Only background, border, width, and visibility take effect. - Expecting the border to show without
border-collapse: collapse. In the separated border model, column borders are ignored. - Miscounting columns. After you add or remove a column, update the
collist so that it still matches the table grid. - Relying on column color alone. A tint is decoration. The table must make sense through its headers and
scopeattributes without it.
Exercise
You write col.price { text-align: right; color: green; background: #f4f4f4; width: 8rem; } and apply the class price to the third col in a table that uses border-collapse: collapse. Which of those four declarations take effect on the cells in that column, and how would you right-align the prices?
Show answer
Only background and width take effect. text-align and color are ignored because cells are not descendants of a col, so they never inherit from it. To right-align the prices, use a cell-level rule such as td:nth-child(3) { text-align: right; }, or put a class like num on each price cell and style that class.
Exercise
A table has four columns. The first is a label. The other three hold numbers and should share a light background. Write the colgroup markup that does this with the fewest elements.
Show answer
<colgroup>
<col>
<col span="3" class="numeric">
</colgroup>
Then add a CSS rule such as col.numeric { background: #eef5ff; }. The span="3" makes one col cover the three numeric columns.