Responsive tables
Make tables scrollable on small screens.
Fitting small screens
Wide tables do not fit small screens; columns overflow and the page grows sideways. The most common fix is to wrap the table in a wrapper and add overflow-x: auto to it.
On the HTML side you only need to put a <table> inside a <div>. You'll see the CSS side in a separate lesson; here we set up only the HTML skeleton. Even so, giving column widths up front with <colgroup> also helps on small screens.
Column layout with colgroup
Setting a table's layout up front reduces overflow on small screens. With <colgroup> and <col> you can give each column a relative width from HTML.
For example, in a four-column table, place one <col> for the first column and one <col span="3"> for the other three. The browser then splits the columns ahead of time. This gives an approximate layout even without CSS; full responsiveness still needs a wrapper.
Exercise Build a responsive table inside a wrapper
Make a table fit small screens. Wrap it in a <div class="table-wrap">. Inside the div place a <table> with a non-empty <caption>, a <colgroup> holding at least two <col> tags, <thead> with <th scope="col"> and <tbody> with <td>.
Show example solution
<div class="table-wrap">
<table>
<caption>Monthly Sales</caption>
<colgroup>
<col>
<col>
<col>
<col>
</colgroup>
<thead>
<tr>
<th scope="col">Month</th>
<th scope="col">Product</th>
<th scope="col">Units</th>
<th scope="col">Revenue</th>
</tr>
</thead>
<tbody>
<tr>
<td>Jan</td>
<td>Headphones</td>
<td>320</td>
<td>$3,200</td>
</tr>
<tr>
<td>Feb</td>
<td>Keyboard</td>
<td>410</td>
<td>$4,100</td>
</tr>
</tbody>
</table>
</div>
Test yourself
-
What is the most common fix for table overflow on small screens?
- Hide the table
- Redraw the table
- Wrap it and scroll with overflow
- Cut columns down to two
Show answer
Wrap it and scroll with overflow — Correct. Wrapping the table in a div with overflow-x: auto is the most common fix.
-
Wrap the table in a wrapper
<div class="table-wrap"> ____ <caption>Monthly sales</caption> <!-- thead and tbody --> </table> </div>Show answer
<div class="table-wrap"> <table> <caption>Monthly sales</caption> <!-- thead and tbody --> </table> </div> -
Match each technique to its role
- Wrapper div
- Small-screen scrolling
- colgroup
- Column-width bridge
- col span
- Covers several columns
- caption
- Titles the table