【问题标题】:Is it possible to split css table into multiple columns?是否可以将 css 表拆分为多列?
【发布时间】:2021-05-05 21:16:55
【问题描述】:

我正在尝试制作一个响应式表格,但我不知道如何实现这一点。谷歌搜索后,找不到解决方案。

所以,我在桌面视图中有这张表:

    1   2   3   

I   B   C   D

II  C   D   E

III D   E   F

IV  E   F   G

我正试图在响应式视图中得到这个:

   1
I     B
II    C
III   D
IV    E

   2
I     C
II    D
III   E
IV    F

etc..

任何形式的帮助将不胜感激

【问题讨论】:

标签: css responsive-design responsive


【解决方案1】:

有几种可用的响应式表格解决方案,包括这种简单的纯 CSS 模式:

data-label 属性 :

首先,我们将为每个数据单元格添加一个 data-label 属性,其值表示该列的名称。这将用于响应式布局中的标签目的。 在较小的视口中,和元素将显示为块级,而不是表格行和单元格。 ::before 伪类现在用作标签。

body {
  font-family: "Open Sans", sans-serif;
  line-height: 1.25;
}

table {
  border: 1px solid #ccc;
  border-collapse: collapse;
  margin: 0;
  padding: 0;
  width: 100%;
  table-layout: fixed;
}

table caption {
  font-size: 1.5em;
  margin: .5em 0 .75em;
}

table tr {
  background-color: #f8f8f8;
  border: 1px solid #ddd;
  padding: .35em;
}

table th,
table td {
  padding: .625em;
  text-align: center;
}

table th {
  font-size: .85em;
  letter-spacing: .1em;
  text-transform: uppercase;
}

@media screen and (max-width: 600px) {
  table {
    border: 0;
  }

  table caption {
    font-size: 1.3em;
  }
  
  table thead {
    border: none;
    clip: rect(0 0 0 0);
    height: 1px;
    margin: -1px;
    overflow: hidden;
    padding: 0;
    position: absolute;
    width: 1px;
  }
  
  table tr {
    border-bottom: 3px solid #ddd;
    display: block;
    margin-bottom: .625em;
  }
  
  table td {
    border-bottom: 1px solid #ddd;
    display: block;
    font-size: .8em;
    text-align: right;
  }
  
  table td::before {
    /*
    * aria-label has no advantage, it won't be read inside a table
    content: attr(aria-label);
    */
    content: attr(data-label);
    float: left;
    font-weight: bold;
    text-transform: uppercase;
  }
  
  table td:last-child {
    border-bottom: 0;
  }
}
<table>
    <thead>
        <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Age</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td data-label="ID">1</td>
            <td data-label="Name">Jake</td>
            <td data-label="Age">23</td>
        </tr>
        <tr>
            <td data-label="ID">2</td>
            <td data-label="Name">Dave</td>
            <td data-label="Age">45</td>
        </tr>
    </tbody>
</table>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-24
    • 1970-01-01
    • 2023-03-07
    • 1970-01-01
    • 1970-01-01
    • 2020-09-15
    • 1970-01-01
    • 2018-11-25
    相关资源
    最近更新 更多