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

Bootstrap 4表格表头旋转文本居中定位问题

解决方案

问题分析

  1. 文本超出单元格:transform: rotate()仅做视觉旋转,元素原始布局空间仍为横向,导致旋转后文本超出单元格边界。
  2. 定位偏差:默认transform-origin: center以元素中点为旋转中心,无法满足底部对齐需求,需调整原点并配合布局属性。

修改后的代码实现

CSS 调整

.table-rotated-header {
  height: 250px;
  /* 用flex实现单元格内文本初始对齐 */
  display: flex;
  align-items: flex-end;
  justify-content: center;
  /* 把旋转原点设为元素底部中点 */
  transform-origin: bottom center;
  /* 旋转后微调位置(数值可根据文本长度调整) */
  transform: rotate(-90deg) translateY(10px);
  /* 强制文本不换行,避免布局混乱 */
  white-space: nowrap;
}
/* 消除表头合并行h3的默认margin,避免间距异常 */
thead tr:first-child th h3 {
  margin: 0;
}

HTML 修正

原代码存在未闭合的<h3>标签,先修正语法错误:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">

<table id="datatable-buttons" class="table table-striped table-bordered dt-responsive nowrap" style="border-collapse: collapse; border-spacing: 0; width: 100%;">

  <thead>
    <tr>
      <th>&nbsp;</th>
      <th colspan="5" class="text-center">
        <h3>Paint</h3>
      </th>
      <th colspan="2" class="text-center">
        <h3>Wheels</h3>
      </th>
      <th colspan="2" class="text-center">
        <h3>Interior</h3>
      </th>
    </tr>
    <tr>
      <th class="table-rotated-header">
        <h5>Country</h5>
      </th>
      <th class="table-rotated-header">
        <h5>White</h5>
      </th>
      <th class="table-rotated-header">
        <h5>Red</h5>
      </th>
      <th class="table-rotated-header">
        <h5>Blue</h5>
      </th>
      <th class="table-rotated-header">
        <h5>Black</h5>
      </th>
      <th class="table-rotated-header">
        <h5>Yellow</h5>
      </th>
      <th class="table-rotated-header">
        <h5>18" Spider</h5>
      </th>
      <th class="table-rotated-header">
        <h5>19" Sport</h5>
      </th>
      <th class="table-rotated-header">
        <h5>Black</h5>
      </th>
      <th class="table-rotated-header">
        <h5>White</h5>
      </th>
    </tr>
  </thead>

  <tbody>
    <tr>
      <td>South Korea</td>
      <td class="text-end">$10,400</td>
      <td class="text-end">$900</td>
      <td class="text-end">$0</td>
      <td class="text-end">$0</td>
      <td class="text-end">Included</td>
      <td class="text-end">$900</td>
      <td class="text-end">$12,200</td>
      <td class="text-end">$6000</td>
      <td class="text-end">$6000</td>
    </tr>
  </tbody>
</table>

关键调整说明

  • flex布局:让表头单元格内的文本先在底部水平居中,再执行旋转操作,保证最终定位符合需求。
  • transform-origin:设置为bottom center后,旋转中心落在元素底部中点,旋转后文本能贴合单元格底部。
  • translateY微调:旋转后可能存在轻微位置偏移,通过纵向位移调整到视觉最优位置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 07:12:04