How to fold table columns into rows on mobile devices?
The solution involves making table cells display: block
on mobile devices, and adding a data-*
attribute to each cell, matching the column name.
This data attribute is injected in the cell's ::before
pseudo-element with content: attr()
.
Example:
<table>
<thead>
<tr>
<th>Pasta</th>
<th>Small</th>
<th>Regular</th>
</tr>
</thead>
<tbody>
<tr>
<td>Spaghetti Bolognese</td>
<td data-th="Small">£5.00</td>
<td data-th="Regular">£7.00</td>
</tr>
<tr>
<td>Lasagna</td>
<td data-th="Small">£5.00</td>
<td data-th="Regular">£7.00</td>
</tr>
</tbody>
</table>
CSS:
@media only screen and (max-width: 40em) {
thead th:not(:first-child) {
display: none;
}
td, th {
display: block;
}
td[data-th]:before {
content: attr(data-th);
}
}
You'll need to add some extra float
to make it pretty.
Working example: http://codepen.io/anon/pen/medrZo