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

响应式表格:换行实现方案及替代方案咨询

实现响应式表格:大屏宽幅展示,移动端垂直堆叠

我明白你想要的是那种在大屏上保持正常表格布局,到了移动端能自动把表格拆成垂直堆叠的键值对样式(替代横向滚动),完全不用依赖JS,纯CSS就能搞定。下面结合你现有的代码,给你一套完整的改造方案:

核心思路

通过CSS媒体查询,在小视口下打破表格的默认布局,把每个数据行转换成类似卡片的结构,同时利用伪元素把表头文本添加到每个数据项前面,模拟出“标签+内容”的垂直展示效果。

改造步骤

1. 给表格单元格添加自定义属性

首先修改你的HTML,给每个<td>标签加上data-label属性,值对应它的表头文本,这样后面CSS可以读取这个值来显示表头:

<div class="floor-plans mb-50 table-responsive">
<table>
<tbody>
<tr>
<td><strong>Rooms</strong></td>
<td><strong>Bathrooms</strong></td>
<td><strong>Size</strong></td>
<td><strong>Price</strong></td>
<td><strong>MLS&reg;#</strong></td>
<td><strong>Type</strong></td>
<td><strong>Maintenance Fee</strong></td>
</tr>
<tr>
<td data-label="Rooms">2</td>
<td data-label="Bathrooms">2</td>
<td data-label="Size">743 sq ft</td>
<td data-label="Price">$628,000</td>
<td data-label="MLS&reg;#">r845621</td>
<td data-label="Type">Highrise</td>
<td data-label="Maintenance Fee">$299</td>
</tr>
</tbody>
</table>
</div>

2. 添加响应式CSS规则

在你现有的CSS基础上,追加媒体查询的样式,这里我设置的断点是768px(你可以根据需求调整为更适合的宽度):

/* 你原有的CSS */
.floor-plans table { width: 100%; margin-bottom: 40px; border: 1px solid rgba(0, 0, 0, 0.07); }
.floor-plans table tr:first-child { border-bottom: 1px solid rgba(0, 0, 0, 0.05); }
.floor-plans table td, table th { padding: 10px 15px; border-right: 1px solid rgba(0, 0, 0, 0.07); }
.floor-plans table td { font-size: 13px; }

/* 新增的响应式样式 */
@media (max-width: 768px) {
  /* 打破表格默认布局,改成块级元素 */
  .floor-plans table,
  .floor-plans tbody,
  .floor-plans tr {
    display: block;
    width: 100%;
  }

  /* 隐藏原来的表头行(我们用伪元素显示表头) */
  .floor-plans tr:first-child {
    display: none;
    border-bottom: none;
  }

  /* 给每个数据行添加边框,模拟卡片效果 */
  .floor-plans tr {
    border: 1px solid rgba(0, 0, 0, 0.07);
    margin-bottom: 15px;
    border-radius: 4px;
  }

  /* 每个单元格改成块级,设置flex布局让标签和内容对齐 */
  .floor-plans td {
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-right: none;
    border-bottom: 1px solid rgba(0, 0, 0, 0.05);
    padding: 12px 15px;
  }

  /* 最后一个单元格去掉底部边框 */
  .floor-plans td:last-child {
    border-bottom: none;
  }

  /* 用伪元素显示表头文本 */
  .floor-plans td::before {
    content: attr(data-label);
    font-weight: bold;
    color: #333; /* 可以根据你的设计调整颜色 */
    font-size: 14px;
  }
}

效果说明

  • 大屏(>768px):完全保留你原来的表格布局,宽幅展示所有列,和之前的效果一致。
  • 小屏(≤768px):每个数据行变成独立的卡片,每个单元格拆成“表头标签+内容”的垂直项,自动换行堆叠,再也不需要横向滚动,完美匹配你想要的效果。

你可以根据自己的设计风格,调整伪元素的颜色、字体大小,或者单元格的内边距、边框样式,让它更贴合你的网站样式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 04:10:21