Responsive Tables

Adapt Tables To Small Screens

<table>s with many columns or long cell contents can overflow their container and cause horizontal scrolling on smaller screens. This simple technique reconfigures tabular data into a mobile friendly, single-column layout.

A data attribute on each content cell stores the value of the corresponding header cell:

HTML
<table>
    <thead>
        <tr>
            <th>Column Label A</th>
            <th>Column Label B</th>
            <th>Column Label C</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td data-th="Column Label A">Content Cell A</td>
            <td data-th="Column Label B">Content Cell B</td>
            <td data-th="Column Label C">Content Cell C</td>
        </tr>
    </tbody>
</table>

Along with styling to hide the header row and rearrange the structure of table elements, the values of these data attributes are then accessed and displayed with a CSS pseudo element:

CSS
@media (max-width:749px) {
    table, tbody, tr, th, td {display:block}
        thead {display:none}
            td::before {content:attr(data-th)": "}
    }

Live Example

Change the width of the screen to switch layouts:

Common Name Scientific Name Class Order Family
Mountain Lion Puma Concolor Mammalia Carnivora Felidae
Mediterranean Gecko Hemidactylus Turcicus Reptilia Squamata Gekkonidae
Gambel's Quail Callipepla Gambelii Aves Galliformes Odontophoridae

Beyond this simple example, the layout and styling can be customized as desired in any number of more complex configurations including multiple columns. The data attributes themselves can also be added and used selectively.

Alternatives

The data attribute technique is a good solution when a <table> is the only option. Depending on the content and desired layouts across screen sizes, in many cases a better alternative (in part, for improved accessibility) is to replace the <table> altogether with other elements like headings and generic containers for even more layout flexibility.