You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用CSS在移动端将表格行转换为独立卡片?

移动端表格转折叠卡片的CSS解决方案

我需要将表格在移动端折叠为独立卡片,使用的表格代码如下:

<table class="table-first">
  <thead>
    <tr>
      <th scope="col">Week</th>
      <th scope="col">Opponent</th>
      <th scope="col">Pass Yards Allowed</th>
      <th scope="col">Pass TDs Allowed</th>
    </tr>
  </thead>
  <tbody>
    <tr style="margin-bottom: 20px; border-bottom: 1px solid;">
      <td data-title="Week">1</td>
      <td data-title="Opponent">Eagles</td>
      <td data-title="Pass Yards Allowed">239</td>
      <td data-title="Pass TDs Allowed">0</td>
    </tr>
    <!-- Additional rows here -->
  </tbody>
</table>

尝试了以下CSS但未生效:

@media screen and (max-width: 767px) {
  .table-first tr {
    display: block;
    margin-bottom: 20px;
    border-bottom: 1px solid;
  }
  
  .table-first td {
    display: block;
  }

  .table-first td::before {
    font-weight: bold;
    margin-right: 6px;
    content: attr(data-title);
    display: inline-block;
  }
}

预期效果为移动端每行表格转为带标题标签的独立卡片样式,正确的CSS代码如下:

@media screen and (max-width: 767px) {
  /* 隐藏移动端不需要的表头 */
  .table-first thead {
    display: none;
  }

  /* 重置表格默认布局,转为块级元素 */
  .table-first {
    display: block;
    width: 100%;
    border-collapse: separate;
    border-spacing: 0;
  }

  /* 将行转为卡片容器,添加卡片样式 */
  .table-first tbody tr {
    display: block;
    margin-bottom: 1.5rem;
    border: 1px solid #ddd;
    border-radius: 8px;
    padding: 1rem;
    background-color: #fff;
  }

  /* 单元格转为块级,实现垂直排列 */
  .table-first tbody td {
    display: block;
    width: 100%;
    margin-bottom: 0.5rem;
    text-align: left;
  }

  /* 利用data-title生成字段前置标题 */
  .table-first tbody td::before {
    content: attr(data-title);
    font-weight: 700;
    display: inline-block;
    width: 120px;
    color: #666;
  }

  /* 移除最后一个单元格的底部间距 */
  .table-first tbody td:last-child {
    margin-bottom: 0;
  }
}

代码说明:

  • 隐藏表头:避免移动端重复显示表头内容,减少冗余
  • 重置表格布局:消除默认表格的单元格均分规则,让卡片布局不受限制
  • 卡片化行元素:通过边框、圆角、内边距模拟卡片视觉效果
  • 固定标题宽度:让每个字段的标题宽度统一,排版更整齐
  • 优化间距:移除最后一个单元格的底部间距,避免卡片底部出现多余空白

内容的提问来源于stack exchange,提问作者dc crage

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 12:46:14