【问题标题】:How could I rotate table header cells and automatically adjust to content size?如何旋转表格标题单元格并自动调整内容大小?
【发布时间】:2025-12-18 12:25:05
【问题描述】:

我正在尝试设计的表格最终会变得有些动态。我希望表格标题单元格出现旋转(以节省水平空间)。我知道可能有更好的方法来节省一些表空间,但是当我在玩一些 HTML 时,我对一些看似不可能的事情产生了兴趣。

在以下代码中,我尝试旋转单元格:

th {
  background-color: #ccc;
}

th,
td {
  border: 1px solid #000;
}

.rotate {
  transform: rotate(-90deg);
  text-align: center;
  margin-bottom: 100px;/* <-- Anything I could do here? */
}
<table cellspacing="0" cellpadding="0">
  <thead>
    <tr>
      <th class="rotate">
        Foo
      </th>
      <th class="rotate">
        Bar
      </th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>
        Foo collection
      </td>
      <td>
        Bar collection
      </td>
    </tr>
  </tbody>
</table>

为了解决我的问题,我在其他几个问题中找到了一些 code,但是这些问题中的大多数都没有解决我遇到的问题:

只要给定表格单元格的内容增加(例如更多字符和/或单词),内容就会流出给定单元格或破坏单元格的外观。

首先,我希望我的表格单元格保持在它们应该在的位置(所以不要像上面小提琴中发生的那样将鼠标悬停在其他单元格上):

其次,我希望能够调整这些单元格内的文本,这意味着单元格必须能够在不破坏表格布局的情况下调整大小:

换句话说:我想在不丢失任何 HTML 表格默认功能的情况下创建旋转的表格标题单元格。是否可以在不破坏表格的情况下旋转表格标题单元格(&lt;th&gt; 元素)?

【问题讨论】:

    标签: javascript html css


    【解决方案1】:

    当你想改变文字的书写方向时,可以使用writing-mode。在这种情况下,我使用writing-mode: vertical-lr;,它使文本垂直,并且容器高度将改变以适应文本。我们还需要原地旋转文本,但将来我会使用sideways-lr,现在缺少支持。

    th {
      background-color: #ccc;
    }
    
    th,
    td {
      border: 1px solid #000;
    }
    
    .rotate span {
      writing-mode: vertical-rl;
      transform: rotate(180deg);
    }
    <table cellspacing="0" cellpadding="0">
      <thead>
        <tr>
          <th class="rotate">
            <span>Foo</span>
          </th>
          <th class="rotate">
            <span>Foo Bar Bazz</span>
          </th>
          <th class="rotate">
            <span>FooBar</span>
          </th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>
            Foo collection
          </td>
          <td>
            Foo Bar Bazz collection
          </td>
          <td>
            Foo Bar collection
          </td>
        </tr>
      </tbody>
    </table>

    作为noted by @AlRo,您需要span 将文本在Firefox 中水平居中。

    【讨论】:

    • 但有一个问题:如果&lt;th&gt; 表头包含多个单词,则出现的单词顺序显示不正确(由于transform: rotate(180deg))(例如,如果它包含单词“foo bar”将显示为“bar foo”)。你知道我该如何解决这个问题吗?
    • 不是旋转引起的。原因是write-mode: vertical-lr; 的呈现方式。您可以使用vertical-rl 更改方向。 (见更新的答案)。
    • 请注意,要在 firefox 和 webkit 上正常工作,您包含的 span 是必需的。作为必需的步骤很容易错过,所以我认为值得一提。在 webkit 上,您只需旋转 td 或 th 即可将其正确居中。
    【解决方案2】:

    如果您要动态更改它们,则创建一个 CSS 类并添加:

    .rotate-text {
        //for old browsers
        -moz-transform: rotate(90deg);
        -webkit-transform: rotate(90deg) ;
        -o-transform: rotate(90deg) ;
        -ms-transform: rotate(90deg) ;
        //for all modern browsers
        transform: rotate(90deg);
    }
    

    现在使用 jQuery 来检查单词数量是否增加了目标,如果为 true,则切换上面在 TD 或 TH 中创建的类

    jQuery("th").toggleClass("rotate-text");
    

    希望对你有帮助。

    【讨论】:

      最近更新 更多