How to build a responsive HTML table that works on mobile
· Category: HTML & CSS
Short answer
Make tables responsive by enabling horizontal scrolling with overflow-x: auto, or restructure rows into card-like layouts on narrow viewports.
Steps
- Wrap the
<table>in a container withoverflow-x: autofor horizontal scrolling. - Alternatively, use CSS to hide table headers and display each cell with a
data-labelattribute on small screens. - Consider using
white-space: nowrapon critical cells to prevent awkward wrapping.
Example
<div class="table-wrapper">
<table>
<thead>
<tr><th>Name</th><th>Role</th><th>Salary</th></tr>
</thead>
<tbody>
<tr>
<td data-label="Name">Alice</td>
<td data-label="Role">Engineer</td>
<td data-label="Salary">$90k</td>
</tr>
</tbody>
</table>
</div>
.table-wrapper {
overflow-x: auto;
}
@media (max-width: 600px) {
thead { display: none; }
tr { display: block; margin-bottom: 1rem; }
td {
display: flex;
justify-content: space-between;
padding: 0.5rem;
border-bottom: 1px solid #ddd;
}
td::before {
content: attr(data-label);
font-weight: bold;
}
}
Tips
- Test with real data to ensure horizontal scrolling does not hide important columns.
- Use
position: stickyon the first column if horizontal scrolling is unavoidable.