Sub topic 3
Styling HTML Tables for Clarity and Small Screens
This chapter assumes you know basic HTML structure and CSS selectors and properties. It focuses on styling columns, accessible multi-level headers, and tables that work on narrow screens.
Styling whole columns with `colgroup` and `col`
Use <colgroup> to describe columns and <col> to apply a style to one or more columns. The span attribute repeats a column definition.
<table>
<caption>Quarterly sales</caption>
<colgroup>
<col class="label-column">
<col span="2" class="number-column">
</colgroup>
<thead>
<tr>
<th scope="col">Product</th>
<th scope="col">Q1</th>
<th scope="col">Q2</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">Books</th>
<td>120</td>
<td>150</td>
</tr>
</tbody>
</table>A <col> can set properties such as background-color, border, and width. Some properties, including text alignment, are more reliable when applied directly to the cells.
Styling tables with CSS
table {
width: 100%;
border-collapse: collapse;
}
th,
td {
border: 1px solid #bbb;
padding: 0.5rem 0.75rem;
text-align: left;
}
caption {
caption-side: top;
font-weight: bold;
text-align: left;
}
.number-column {
background-color: #f5f8ff;
}
tbody tr:nth-child(even) {
background-color: #fafafa;
}border-collapse: collapse joins adjacent borders. Padding gives cell content room to breathe. Row striping helps readers track across a wide row.
Multi-level headers with `id` and `headers`
For simple tables, scope usually connects headers and data. For complex tables, give each header an id. Each data cell then lists every related header in its headers attribute.
<th id="sales" colspan="2">Sales</th>
<th id="q1" headers="sales">Q1</th>
<td headers="north sales q1">120</td>This explicit mapping helps screen readers announce the correct context.
Handling wide tables on small screens
Keep the table intact and allow its container to scroll horizontally.
<div class="table-scroll" tabindex="0" role="region" aria-label="Quarterly sales table">
<table>...</table>
</div>.table-scroll {
overflow-x: auto;
}The keyboard-focusable region lets keyboard users discover the scrolling area.
Common mistakes and legacy attributes to avoid
- Do not use tables for page layout. Use CSS Grid or Flexbox instead.
- Do not omit headers when rows or columns need labels.
- Make sure
colspanandrowspanpreserve the table’s rectangular grid. - Prefer CSS over old attributes such as
border,cellpadding,cellspacing,align, andbgcolor.
Exercise
When should you use headers instead of only scope?
Show answer
Use headers when a data cell relates to multiple header levels and needs an explicit list of header IDs.