Responsive table with horizontal scroll in CSS
12 A table that stays readable
fairStyle a data table so it reads well: aligned columns, a distinguishable header, and horizontal scrolling rather than overflow on a narrow screen.
Stuck? Three hints, smallest first
- 1.
border-collapse: collapseremoves the double borders between cells. - 2. Numbers belong right-aligned; text belongs left-aligned. Mixed alignment is hard to scan.
- 3. Wrap the table in a container with
overflow-x: autoso it scrolls instead of breaking the page.
<div class="tablewrap">
<table>
<caption>Fares from Jibowu</caption>
<thead>
<tr><th scope="col">Route</th><th scope="col">Seats</th><th scope="col">Fare</th></tr>
</thead>
<tbody>
<tr><td>Lagos – Abuja</td><td class="num">14</td><td class="num">₦18,000</td></tr>
<tr><td>Lagos – Kano</td><td class="num">30</td><td class="num">₦22,000</td></tr>
</tbody>
</table>
</div>
.tablewrap {
overflow-x: auto; /* scroll the table, do not break the page */
}
table {
width: 100%;
border-collapse: collapse; /* one border between cells, not two */
font-size: 0.9rem;
}
caption {
text-align: left;
padding-bottom: 8px;
color: #5b5c63;
font-weight: 600;
}
th, td {
padding: 8px 10px;
border-bottom: 1px solid #e4e5e9;
text-align: left;
}
th {
background: #f2f3f5;
font-weight: 600;
}
/* Numbers read far better right-aligned, so the digits line up. */
.num { text-align: right; font-variant-numeric: tabular-nums; }
9 checks that prove this answer
Assertions, run in the browser. The markup and styles above are handed to them
as html and css, so press Run and each check prints
ok. The build fails if a single one fails.
test('borders are collapsed', declares(css, 'border-collapse', 'collapse'), true);
test('the table can scroll rather than overflow', declares(css, 'overflow-x', 'auto'), true);
test('numbers are right aligned', /\.num\s*\{[^}]*text-align\s*:\s*right/.test(css), true);
test('and use tabular figures so digits line up', /tabular-nums/.test(css), true);
test('the header is distinguishable', /th\s*\{[^}]*background/.test(css), true);
test('a caption names the table', hasTag(html, 'caption'), true);
test('proper thead and tbody', hasTag(html, 'thead') && hasTag(html, 'tbody'), true);
test('header cells declare their scope', /scope="col"/.test(html), true);
test('three columns', countTag(html, 'th'), 3);
Output
Two accessibility details do real work here. scope="col" tells a screen reader that each <th> heads a column, so when the user lands on a cell it can announce "Fare, ₦22,000" rather than just the number. And <caption> names the table, which is how someone scanning by table gets to the right one. On the visual side, font-variant-numeric: tabular-nums makes every digit the same width so columns of figures align.