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

如何使用CSS实现HTML表格行列互换 适配移动端显示需求

实现方案

直接替换你现有的CSS代码即可实现需求,不需要修改原有HTML结构,如果需要更好的扩展性可以参考后面的优化方案。

table, th, td {
  border:1px solid black;
  border-collapse: collapse;
}
@media screen and (max-width: 768px) { 
  /* 打破原有表格布局,全部转为块级元素 */
  table, tbody, tr, td, th {
    display: block;
    width: 100%;
    box-sizing: border-box;
  }
  /* 隐藏原有横向表头 */
  tr:first-child {
    display: none;
  }
  /* 调整单元格样式,给伪元素预留位置 */
  td {
    padding: 8px 8px 8px 50%;
    text-align: right;
    position: relative;
  }
  /* 伪元素插入对应表头内容 */
  td:nth-child(1)::before { content: "A"; }
  td:nth-child(2)::before { content: "B"; }
  td:nth-child(3)::before { content: "C"; }
  td:nth-child(4)::before { content: "D"; }
  td:nth-child(5)::before { content: "E"; }
  td:nth-child(6)::before { content: "F"; }
  td:nth-child(7)::before { content: "G"; }
  /* 表头样式调整 */
  td::before {
    position: absolute;
    left: 8px;
    width: calc(50% - 8px);
    text-align: left;
    font-weight: bold;
  }
}

可选优化方案(推荐)

如果后续可能修改表头、或者表格有多行数据,可以给每个td增加data-label属性绑定表头内容,后续不需要同步修改CSS,适配性更强。
修改后的HTML表格部分:

<table style="width:100%">
  <tr>
    <th>A</th>
    <th>B</th>
    <th>C</th>
    <th>D</th>
    <th>E</th>
    <th>F</th>
    <th>G</th>
  </tr>
  <tr>
    <td data-label="A">1</td>
    <td data-label="B">2</td>
    <td data-label="C">3</td>
    <td data-label="D">4</td>
    <td data-label="E">5</td>
    <td data-label="F">6</td>
    <td data-label="G">7</td>
  </tr>
</table>

对应CSS媒体查询里的伪元素部分替换为下面的代码即可:

td::before {
  content: attr(data-label);
  position: absolute;
  left: 8px;
  width: calc(50% - 8px);
  text-align: left;
  font-weight: bold;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 03:36:03