I created a drop-in solution for supporting tables on small screens.

Download View on Github

I’m a pretty big fan of the Bootstrap framework (so long as you take care to make sure your site doesn’t look like everyone else’s). But even in modern web design, sometimes you still need to support tables (because it makes sense, semantically, to use table tags when you display tabular data). I’ve been iterating on this for a while, but the first version of my responsive tables didn’t use table tags at all. In fact, they were written like this:

<section class="table">
  <header class="thead">
    <p class="tr">
      <span class="th">
  <div class="tbody">
    <p class="tr">
      <span class="td">

I could have just used div tags all the way through, but I wanted to give it some semblance of meaning through different tags. Ultimately, though, I had to define custom styles for classes named after the table tags. As first attempts go, it wasn’t bad, and it worked across all browsers.

But web design, as I like to say, is about iteration and improvement. And the next time around, I felt it was important to keep those table tags intact.

The final solution (what I’m releasing) doesn’t necessarily require Bootstrap, but it is written with its .table base class in mind. All you need to do is add one of two classes — “table-collapse-phone” or “table-collapse-tablet” to the <table> tag, like so:

<table class="table table-collapse-phone">

The .table-collapse-phone class, as its name implies, will make the table’s cells collapse into block-level elements when the viewport is less than 480 pixels wide (Bootstrap’s default for “phone” widths). The .table-collapse-tablet class will collapse the table on widths less than 768 pixels (likewise, for tablet widths).

There is one last bit of functionality I’d like to mention. By default, collapsing the table’s columns into block-level elements will remove the header completely, resulting in columns with no labels. I found that I can get around this by using a data attribute, like so:

<td data-label="Name">

The accompanying stylesheet can target that using a pseudo-element:

[data-label]:before {
  content: attr(data-label);

To accommodate the prepended label, the stylesheet would have to indent the column itself. However, not all of your columns may need a label, and you would still want the values indented. To get around this, add the class “has-label” to each column for which you want indented with a label.

<td class="has-label" data-label="Name">

Problems? Solutions? Ideas? Let me know what you think by leaving a comment below or submitting an issue on the repo.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.