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

如何用CSS实现Excel样式的倾斜表头?已尝试Flex布局

实现Excel式倾斜表头的CSS方案

可以用CSS实现这种Excel风格的倾斜表头效果,你当前的Flex布局方案存在元素重叠、排版错乱的问题,下面是优化后的实现方案:

问题分析

你直接对Flex容器内的元素应用transform: rotate(-45deg),但元素的布局占位空间仍保持水平状态,导致旋转后的内容互相重叠,无法达到截图中的整齐效果。

优化实现方案

我们采用语义化的表格结构,通过分离表头单元格的占位空间与文字元素,配合定位和旋转属性实现需求:

HTML代码

<table class="tilted-header-table">
  <thead>
    <tr>
      <th><span>Column 1</span></th>
      <th><span>Column 2</span></th>
      <th><span>Column 3</span></th>
      <th><span>Column 4</span></th>
      <th><span>Column 5</span></th>
      <th><span>Column 6</span></th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Data 1</td>
      <td>Data 2</td>
      <td>Data 3</td>
      <td>Data 4</td>
      <td>Data 5</td>
      <td>Data 6</td>
    </tr>
    <tr>
      <td>Data 7</td>
      <td>Data 8</td>
      <td>Data 9</td>
      <td>Data 10</td>
      <td>Data 11</td>
      <td>Data 12</td>
    </tr>
  </tbody>
</table>

CSS代码

.tilted-header-table {
  border-collapse: separate;
  border-spacing: 0;
  margin: 20px;
}

.tilted-header-table th {
  position: relative;
  height: 80px;
  width: 60px;
  border: 1px solid #000;
  padding: 0;
  overflow: visible;
  background: #fff;
}

.tilted-header-table th span {
  position: absolute;
  bottom: 8px;
  left: 50%;
  transform: translate(-50%, 0) rotate(-45deg);
  transform-origin: bottom center;
  white-space: nowrap;
}

.tilted-header-table td {
  border: 1px solid #000;
  padding: 8px;
  text-align: center;
  width: 60px;
}

方案说明

  1. 语义化结构:使用<table>、<th>等标签构建表头,比Flex布局更适配表格场景
  2. 分离布局与内容:表头单元格(<th>)负责占据固定布局空间,内部<span>单独承载文字并旋转,避免旋转影响整体排版
  3. 精确对齐:通过transform-origin: bottom center让文字围绕底部中心旋转,配合translate(-50%, 0)实现水平居中,对齐效果贴近Excel截图
  4. 边界控制:border-collapse: separate确保单元格边框不重叠,保持清晰网格线

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 13:43:04