How to fold table columns into rows on mobile devices?

Benjamin picture Benjamin · Aug 30, 2015 · Viewed 14.4k times · Source

I'm developing a website featuring a restaurant's menu. Each item is available in different sizes, each at a different price. This is displayed on medium and large devices using a table, with a column for each price:

Menu in columns

On mobile devices, the screen is too narrow to properly display up to 4 different sizes per product.

So I would like to fold columns into rows, having each row starting with the column name:

enter image description here

Is there anything like this possible using a responsive design? I'm trying to avoid maintaining two different HTML versions of the content, one visible only on mobile, and one visible only on larger screens.

I'm using Foundation 5, so I'm ideally looking for a solution using this grid system, but I'm open to any solution really.

Answer

Benjamin picture Benjamin · Aug 31, 2015

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