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

如何实现表格单元格文本垂直逆时针排列?附现有代码

解决方案:实现垂直逆时针排列的自适应表格单元格文本

要解决你的需求,我们可以结合CSS的书写模式或变换属性,再配合容器查询实现自适应(单元格宽时水平居中,窄时垂直逆时针排列),以下是两种可行方案:


方案1:使用writing-mode实现原生垂直逆时针排版

这种方法依赖CSS原生的书写模式,无需变换,兼容性更好,适合多语言场景:

完整代码

/* 表格基础样式,确保单元格尺寸可控 */
table {
  table-layout: fixed;
  width: 100%;
  border-collapse: collapse;
}

td {
  border: 1px solid #ddd;
  height: 120px; /* 给竖排文本预留足够高度 */
}

/* 容器用于居中对齐,支持容器查询 */
.rotate-container {
  container-type: inline-size;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}

/* 默认垂直逆时针排列 */
.rotate {
  writing-mode: vertical-lr; /* 垂直从左到右排列,对应逆时针方向 */
  text-orientation: mixed; /* 自动适配文字方向,英文会逆时针旋转90度 */
}

/* 当单元格宽度≥200px时,切换为水平居中 */
@container (min-width: 200px) {
  .rotate {
    writing-mode: horizontal-tb; /* 恢复水平排版 */
    text-orientation: initial;
    text-align: center;
  }
}
<table>
  <tr>
    <td></td>
    <td>choice 1</td>
    <td>choice 2</td>
    <td>total</td>
  </tr>
  <tr>
    <td>
      <div class="rotate-container">
        <div class="rotate">choice 3 (this is a long text test case)</div>
      </div>
    </td>
    <td></td>
    <td></td>
    <td></td>
  </tr>
  <tr>
    <td>
      <div class="rotate-container">
        <div class="rotate">choice 4</div>
      </div>
    </td>
    <td></td>
    <td></td>
    <td></td>
  </tr>
  <tr>
    <td>total</td>
    <td></td>
    <td></td>
    <td></td>
  </tr>
</table>

说明

  • writing-mode: vertical-lr:让文本垂直从左到右排列,视觉上对应逆时针方向(和你之前的vertical-rl顺时针方向正好相反)。
  • container-type: inline-size:开启容器查询,让样式根据单元格(容器)的宽度自适应,而非视口宽度。
  • Flex布局确保文本在单元格内始终居中,无论水平还是垂直状态。

方案2:使用transform: rotate(-90deg)实现直观逆时针旋转

如果你需要更直观的“逆时针旋转90度”效果(比如英文文本保持阅读习惯的倒转),可以用变换属性:

完整代码

table {
  table-layout: fixed;
  width: 100%;
  border-collapse: collapse;
}

td {
  border: 1px solid #ddd;
  height: 120px;
}

.rotate-container {
  container-type: inline-size;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  overflow: visible; /* 避免旋转后文本被截断 */
}

.rotate {
  transform: rotate(-90deg); /* 逆时针旋转90度 */
  white-space: nowrap; /* 长文本不换行,保持竖排连贯性 */
}

@container (min-width: 200px) {
  .rotate {
    transform: none; /* 取消旋转 */
    white-space: normal;
    text-align: center;
  }
}

说明

  • transform: rotate(-90deg):直接将文本逆时针旋转90度,视觉效果更直观。
  • white-space: nowrap:确保长文本在竖排时不会被拆分,保持整体可读性。
  • 同样通过容器查询实现自适应,宽单元格时自动切换为水平居中。

兼容性提示

  • 容器查询(@container)支持Chrome 105+、Firefox 110+、Safari 16.4+,如果需要兼容旧浏览器,可以改用媒体查询(基于视口宽度),或者用JavaScript动态判断单元格宽度。
  • writing-mode和text-orientation在现代浏览器中都有良好支持。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 08:03:09