Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fold table columns into rows on mobile devices?

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.

like image 676
BenMorel Avatar asked Aug 30 '15 21:08

BenMorel


People also ask

How do you make a table with rows and columns?

You can create a table using the <table> element. Inside the <table> element, you can use the <tr> elements to create rows, and to create columns inside a row you can use the <td> elements. You can also define a cell as a header for a group of table cells using the <th> element.


1 Answers

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

like image 94
BenMorel Avatar answered Nov 10 '22 05:11

BenMorel