Nat TaylorBlog, Web Design & East Boston

Responsive Tables

Published on

Tables and skinny screens don’t play nice. In some cases it would be better if the table was presented more like a list, where columns were stacked vertically. This is easy thanks to ::before, content and attr().

For each <td> set data-label to the heading (client or server side), then add CSS for td::before {content: attr(data-label);} td,tr {display:block;} thead {display:none;} within a media query and viola: the table presents nicely on a skinny screen!

Demo

foobarbaz
lorem ipsum dolor blah blah foo bar lorem ipsum dolor blah blah foo bar lorem ipsum dolor blah blah foo bar
lorem ipsum dolor blah blah foo bar lorem ipsum dolor blah blah foo bar lorem ipsum dolor blah blah foo bar
lorem ipsum dolor blah blah foo bar lorem ipsum dolor blah blah foo bar lorem ipsum dolor blah blah foo bar
lorem ipsum dolor blah blah foo bar lorem ipsum dolor blah blah foo bar lorem ipsum dolor blah blah foo bar

Code

<button onclick="document.querySelector('#demo').classList.toggle('demo')">Demo</button>
<table id="demo">
<thead><tr><th>foo</th><th>bar</th><th>baz</th></tr></thead>
<tbody>
<tr>
<td data-label="foo">lorem ipsum dolor blah blah foo bar</td>
<td data-label="bar">lorem ipsum dolor blah blah foo bar</td>
<td data-label="baz">lorem ipsum dolor blah blah foo bar</td>
</tr>
<tr>
<td data-label="foo">lorem ipsum dolor blah blah foo bar</td>
<td data-label="bar">lorem ipsum dolor blah blah foo bar</td>
<td data-label="baz">lorem ipsum dolor blah blah foo bar</td>
</tr>
<tr>
<td data-label="foo">lorem ipsum dolor blah blah foo bar</td>
<td data-label="bar">lorem ipsum dolor blah blah foo bar</td>
<td data-label="baz">lorem ipsum dolor blah blah foo bar</td>
</tr>
<tr>
<td data-label="foo">lorem ipsum dolor blah blah foo bar</td>
<td data-label="bar">lorem ipsum dolor blah blah foo bar</td>
<td data-label="baz">lorem ipsum dolor blah blah foo bar</td>
</tr>
</tbody>
</table>
<style>
td {border:1px solid black}
.demo td {border: 0; display:block;}
.demo td::before {content: attr(data-label) ": ";color:#666;}
.demo thead {display:none;}
.demo tr {border-radius:0.5em;padding:0.5em;border:1px solid black;display:block;margin-bottom:1em;}
</style>

Popular Posts

Post Navigation

«