如何在移动设备上将 table 列折叠成行?

How to fold table columns into rows on mobile devices?

我正在开发一个以餐厅菜单为特色的网站。每件商品都有不同的尺寸,价格也不同。这在使用 table 的中型和大型设备上显示,每个价格都有一列:

在移动设备上,屏幕太窄,无法正确显示每个产品最多 4 种不同的尺寸。

所以我想将列折叠成行,每行以列名开头:

是否可以使用响应式设计实现类似的功能?我试图避免维护内容的两个不同 HTML 版本,一个仅在移动设备上可见,一个仅在大屏幕上可见。

我正在使用 Foundation 5,所以我正在寻找使用此网格系统的理想解决方案,但我对任何解决方案都持开放态度。

解决方案包括在移动设备上制作 table 个单元格 display: block,并向每个单元格添加一个 data-* 属性,匹配列名。

此数据属性通过 content: attr().

注入到单元格的 ::before 伪元素中

示例:

<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);
    }
}

您需要添加一些额外的东西 float 以使其更漂亮。

工作示例:http://codepen.io/anon/pen/medrZo

CSS 上述结果的变化

table {
    border-spacing: 0;
    }

    td,
    th {
    padding: 0.5em;
    }

    th {
    font-weight: bold;
    text-align: left;
    }

    thead th {
    background-color: #999;
    color: white;
    }

    td > div {
    float: right;
    }
@media screen and (max-width: 885px) {
thead th:not(:first-child) {
    display: none;
}

thead th:first-child:after {
    content: "'s";
}

td, th {
    display: block;
    width: 100% !important;
}
td:first-child {
    font-weight: bold;
}

td[data-th]:before {
    content: attr(data-th);
    border-radius: 10px 0px 0px 10px;
    font-weight: bold;
    min-width: 10rem;
    display: inline-block;
}

}