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

  1. Wrap the <table> in a container with overflow-x: auto for horizontal scrolling.
  2. Alternatively, use CSS to hide table headers and display each cell with a data-label attribute on small screens.
  3. Consider using white-space: nowrap on 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: sticky on the first column if horizontal scrolling is unavoidable.