Sub topic 9
Styling Tables with CSS
Browsers draw a plain table with no borders and tight cells. CSS turns that into something readable. Tables follow their own layout rules, so some familiar properties behave differently here. This chapter covers how table borders work, how to space and align cells, how to stripe rows, and how to style columns and fix a header in place.
What you need first
This chapter assumes you can write a table with table, tr, th, and td, and that you know thead, tbody, tfoot, caption, and colgroup. It also assumes you can write CSS selectors and declarations, including pseudo-classes such as :nth-child(). Styling should never replace the structure from earlier chapters. Keep the semantic elements and let CSS control the appearance.
The two border models
CSS has two models for table borders, chosen by the border-collapse property.
separateis the default. Every cell has its own border, andborder-spacingleaves a gap between neighbouring cells. Two adjacent cells with 1px borders show a double line.collapsemerges neighbouring borders into one shared line. There is noborder-spacing, and the browser resolves conflicts between borders (for example a thick border next to a thin one).
Most designs use collapse because it gives clean grid lines.
When two collapsed borders meet, the wider one wins. If the widths are equal, the style decides, in this order: double, solid, dashed, dotted, and so on. hidden beats everything and removes the border. If width and style are equal, the border from the cell that comes later in the source wins.
A baseline stylesheet
This set of rules works for most data tables. It merges borders, pads the cells, shades the header, stripes alternate rows, and places the caption.
table {
border-collapse: collapse;
width: 100%;
}
th,
td {
border: 1px solid #ccc;
padding: 0.5rem 0.75rem;
text-align: left;
}
thead th {
background: #f0f0f0;
}
tbody tr:nth-child(even) {
background: #fafafa;
}
caption {
caption-side: top;
font-weight: bold;
text-align: left;
}Some details in these rules matter:
- The
bordergoes onthandtd, not only ontable. A border ontableoutlines the whole grid, and the cells inside stay unbordered. paddinggoes on the cells. Padding ontabledoes nothing useful, andtrtakes neither padding nor margin.- The stripe selector starts at
tbody. A baretr:nth-child(even)would also stripe the header row and the footer row. - Browsers center
thtext by default. Thetext-align: leftrule overrides that. Many designs also align header text to match the column below it.
Spacing and alignment
Four properties control the space and position of content inside cells.
| Property | Applies to | Effect |
|---|---|---|
| `padding` | `th`, `td` | Space between the cell border and its content |
| `border-spacing` | `table` (separate model only) | Gap between cells |
| `text-align` | cells, rows, or the table | Horizontal alignment of content |
| `vertical-align` | `th`, `td` | Vertical position of content in the cell. The default is `middle`. |
vertical-align has a catch. On table cells it means alignment within the row's height. On other elements it means something else. If one cell holds a long paragraph and its neighbours hold a single word, vertical-align: top often looks tidier than the middle default:
td {
vertical-align: top;
}Align numbers to the right so that digits line up by place value. Combine that with font-variant-numeric: tabular-nums, which makes every digit the same width in fonts that support it:
td.numeric,
th.numeric {
text-align: right;
font-variant-numeric: tabular-nums;
}Use border-spacing only with border-collapse: separate. It takes one value for equal gaps or two values for horizontal and vertical gaps. Separate borders also allow border-radius on cells, which has no effect on collapsed borders.
.cards {
border-collapse: separate;
border-spacing: 0 0.5rem;
}
.cards td {
background: #f4f4f4;
}
.cards td:first-child {
border-radius: 6px 0 0 6px;
}
.cards td:last-child {
border-radius: 0 6px 6px 0;
}The empty-cells property, valid only in the separate model, controls whether empty cells draw borders and backgrounds. Its values are show (the default) and hide.
Striping and hover
The :nth-child() pseudo-class counts sibling elements, so tbody tr:nth-child(even) counts the rows inside one tbody. Two cases make the pattern less obvious than it looks:
- Each
tbodyrestarts the count. A table with severaltbodygroups gets stripes that restart in every group. - Cells that use
rowspanmake a row look shorter than it is. A stripe still covers the entiretr, but the spanning cell reaches into rows below it, so the pattern can look uneven. Check the result visually when you mix spans with striping.
For hover highlighting, target the row:
tbody tr:hover {
background: #e8f1ff;
}Hover is not a substitute for clear structure. Touch screens and keyboard users never trigger it, so treat it as an extra.
Pick stripe colours with enough contrast against the text. A pale grey #fafafa next to white is a subtle effect. If you want the stripe to carry meaning, there is a problem, because colour alone should never be the only signal.
Styling columns with col
The colgroup and col elements let you target a whole column without repeating a class on every cell. This example marks the last two columns:
<table>
<colgroup>
<col>
<col span="2" class="numeric">
</colgroup>
<tr>
<th scope="col">City</th>
<th scope="col">Population</th>
<th scope="col">Area</th>
</tr>
<tr>
<td>Oslo</td>
<td>700000</td>
<td>454</td>
</tr>
</table>Here <col span="2"> covers two columns. A rule such as col.numeric { background: #eef5ff; } then shades both.
Column elements are limited. Only four properties apply to them:
border(and only withborder-collapse: collapse)backgroundwidthvisibility(the valuecollapseremoves the column)
Setting text-align, color, or font-weight on a col does nothing, because the cells are not children of the column in the document tree, so those properties do not inherit down to them. For those you need a selector on the cells. To right-align the last two columns of a three-column table, write:
td:nth-child(n + 2),
th:nth-child(n + 2) {
text-align: right;
}Spanned cells make nth-child unreliable, because a cell's position among its siblings no longer matches its column. In tables with colspan or rowspan, put a class on the cells.
Table layout and width
Browsers use one of two algorithms for column widths, set by table-layout.
autois the default. The browser reads the content of every cell, then computes column widths. Content can change the widths, and large tables render slowly because the browser needs all rows before it can lay out anything.fixedtakes widths from the table'swidthand from the first row (or fromcolelements). The browser can start drawing at once, and later rows cannot change the widths. Long words overflow instead of widening the column, so pair it withoverflow-wrap.
table.fixed {
table-layout: fixed;
width: 100%;
}
table.fixed td {
overflow-wrap: anywhere;
}With table-layout: fixed, set column widths on col elements. This avoids writing widths on cells:
col.name { width: 40%; }
col.amount { width: 15ch; }In the auto algorithm, width on a cell is a hint, not a command. The browser raises it to fit the content's minimum width. Use max-width carefully on cells, since it is undefined for table cells in the CSS specification and browsers differ. A wrapper element or table-layout: fixed gives more predictable results.
Keeping the header visible
For a long table, you can pin the header row while the page scrolls with position: sticky:
<style>
.scroller {
max-height: 16rem;
overflow-y: auto;
}
table {
border-collapse: separate;
border-spacing: 0;
width: 100%;
}
th,
td {
border-bottom: 1px solid #ccc;
padding: 0.5rem 0.75rem;
text-align: left;
}
thead th {
position: sticky;
top: 0;
background: #f0f0f0;
}
</style>
<div class="scroller">
<table>
<caption>Long list</caption>
<thead>
<tr><th scope="col">Item</th><th scope="col">Cost</th></tr>
</thead>
<tbody>
<tr><td>Rent</td><td>900</td></tr>
<tr><td>Food</td><td>300</td></tr>
<tr><td>Travel</td><td>150</td></tr>
<tr><td>Phone</td><td>40</td></tr>
<tr><td>Books</td><td>60</td></tr>
<tr><td>Gym</td><td>35</td></tr>
<tr><td>Savings</td><td>250</td></tr>
<tr><td>Insurance</td><td>120</td></tr>
<tr><td>Internet</td><td>45</td></tr>
<tr><td>Water</td><td>30</td></tr>
</tbody>
</table>
</div>Three details make this work:
- The
thelements are sticky, not thetheador thetr. Support for sticky on those elements is less consistent across browsers. - The sticky header needs a background. Without one, rows scroll visibly under the text.
- The example uses
border-collapse: separatewithborder-spacing: 0. Undercollapse, borders belong to the table, not to the cell, so they do not move with a sticky header and appear to vanish or stay behind. Usingseparatewith zero spacing avoids that and looks the same as a collapsed grid.
Pitfalls
- Using
displayon table elements. Settingdisplay: blockordisplay: flexon atable,tr, ortdremoves the table layout behaviour. Some browsers also drop the element's table semantics for assistive technology. If you need a different layout, check the result with a screen reader, or restyle with care and add the ARIA roles back. - Hiding structure with CSS.
display: noneon a header cell removes it from the accessibility tree too. - Expecting
trto behave like a box. Rows take backgrounds and borders (collapsed model only), but not margin or padding. - Relying on colour. Striping, hover, and shading are decoration. The structure should read correctly without them.
- Mixing
borderontableand cells underseparate. You get nested outlines and double lines. Choose one model deliberately.
Exercises
Exercise
A table has border: 1px solid #ccc on every td, and you see double lines between the cells. Which single declaration on the table fixes it, and why does it work?
Show answer
border-collapse: collapse;. The default is separate, where every cell draws its own border, so two neighbouring borders sit side by side. Collapsing merges the adjacent borders into one shared line.
Exercise
You write col.price { text-align: right; } and nothing changes. Why, and what do you write instead?
Show answer
Only border, background, width, and visibility apply to col, and cells do not inherit properties from it. Put the rule on the cells instead, with a class such as td.price { text-align: right; }, or with td:nth-child(3) when there are no spanned cells.
Exercise
Your sticky header scrolls away from its borders when the table uses border-collapse: collapse. Name two ways to fix it.
Show answer
Switch to border-collapse: separate with border-spacing: 0 and put the borders on the cells, or draw the line with a box-shadow on the sticky th. Both keep the line attached to the header cell.