Responsive Tables

I recently discovered Flexbox, and I’m glad I did. Alignment issues are all but eliminated which makes developing complex layouts more enjoyable and a lot faster. I used it on a recent website project to create a simple responsive grid and other layout containers ┬áThat was exciting enough, but the real breakthrough came when I had to put in a pricelist.

The best presentation for the information was a table. Tables get a bad reputation, but they are really good at displaying grids of information. They do, however, suck at being responsive – or so I thought.

The solution I used isn’t perfect. But it was fast, easy, and worked perfectly – I simply turned the appropriate table elements into flex containers when the screen got too small to display the table, and let Flexbox deal with everything!

There’s not much too it. Step one was turning the table, tbody, and tr elements into vertical flex containers. The td elements became horizontal flex containers with spacing around the inner elements, and that was it. The table responded to the change in screen size perfectly with a single column of stacked cells.

Only one problem remained: the table headers, although stacked in a neat column, were at the top of the table. Not cool – you don’t know what the data means once you scroll down. I decided that some extra markup, hidden by default, was the best way to go. So I put a span into each table cell and the span contained the heading of the column. When the table gets skinny, the thead is hidden and the spans are displayed. The result is a stack of cells, each containing a label and the associated data.

Even though this works well, it has some issues. The main problem is the duplication of header data. I have seen other solutions that use :before selectors in CSS to put the headers in, but now you’re putting content into your CSS and that doesn’t feel right. It also makes generating dynamic tables harder because you need to generate the CSS as well.

At the end of the day, I got a responsive table with very little effort. I think the principle is sound and once we get a solution to the duplicated headers it’ll be the dawn of a new era… or, you’ll have more fun building websites and that’s always good!

Leave a Reply

Your email address will not be published. Required fields are marked *

A less annoying captcha to prove you're a person