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

如何用CSS实现垂直旋转表格表头文本自动换行不溢出

可换行垂直旋转表头实现方案

原代码直接对文本节点应用旋转,未处理transform属性不改变元素文档流占位的特性,同时存在无效选择器、缺少换行规则、无打印适配的问题,会导致长文本溢出、尺寸失控。以下是修复后的完整实现,满足所有需求:


完整实现代码

CSS样式

/* 基础表格边框样式 */
table, th, td {
  border: 1px solid black;
  border-collapse: collapse;
}

/* 表头单元格控制:高度可在150px-300px区间按需调整 */
th {
  height: 200px; /* 此处为默认值,可根据文本长度修改 */
  width: 32px;
  padding: 0;
  font-weight: normal;
  position: relative;
  vertical-align: bottom;
}

/* 旋转文本容器:实现自动换行、居中定位 */
.rotate {
  position: absolute;
  left: 50%;
  top: 50%;
  /* 旋转+居中定位 */
  transform: translate(-50%, -50%) rotate(-90deg);
  /* 容器宽度比表头高度小20px,预留内边距空间 */
  width: 180px;
  /* 自动断词换行规则,解决长文本溢出 */
  white-space: normal;
  overflow-wrap: break-word;
  word-break: break-word;
  text-align: center;
  line-height: 1.4;
}

/* A4打印适配,优化单页列容纳量 */
@media print {
  @page {
    size: A4 portrait;
    margin: 10mm;
  }
  table {
    width: 100%;
    table-layout: fixed;
  }
  td {
    padding: 2px 4px;
    font-size: 12px;
  }
  th {
    /* 打印场景下调低表头高度,容纳更多列 */
    height: 160px;
  }
  .rotate {
    width: 140px;
    font-size: 11px;
  }
}

HTML结构

移除原代码中内联的冗余word-wrap样式,结构保持简洁:

<table>
  <tr>
    <th><div class="rotate">Header 1</div></th>    
    <th><div class="rotate">Big Headerrrrrrrrrrrrr</div></th>
    <th><div class="rotate">Header 3</div></th>
    <th><div class="rotate">Header 4</div></th>
    <th><div class="rotate">Header 5</div></th>
  </tr>
  <tr>
    <td>Value 1</td>
    <td>Value 2</td>
    <td>Value 3</td>
    <td>Value 4</td>
    <td>Value 5</td>
  </tr>
</table>

调整说明

  • 表头高度修改:直接调整th的height属性即可,取值范围150px-300px,调整后同步修改.rotate的width值(比th的height小20px左右预留边距),即可适配不同长度的表头文本
  • 换行规则已兼容中英文、连续长字符串,所有文本都会在限定宽度内自动断行,不会溢出单元格边界
  • 打印样式默认做了边距、字号优化,A4幅面下单页可容纳15列以上常规内容,不会出现异常分页、内容裁切问题
  • 已移除原代码中IE6/IE8的老旧兼容滤镜,避免打印渲染异常,现代浏览器、主流办公软件的打印功能均可正常识别样式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.01 14:01:27