【问题标题】:Rotate text and shrink its container to the new width旋转文本并将其容器缩小到新宽度
【发布时间】:2015-04-28 18:39:34
【问题描述】:

我想旋转一些文本以进行垂直显示(y 轴图表标签)。文本可以是任何可变长度(但总是在一行上)。

我尝试使用 CSS3 变换 进行旋转(参见 JSFiddle):

.rotate {
   transform: rotate(270deg);
}

但是,即使旋转后,元素的原始宽度和高度也会保留,如described in the spec

在 HTML 命名空间中,transform 属性不会影响转换后元素周围内容的流动。

这意味着元素的容器宽度会根据标签文本长度扩大,影响相邻图表的位置。

如何旋转文本并将其容器缩小到新宽度?任何解决方案都会有所帮助,包括 JavaScript/jQuery 解决方案或替代方法。

【问题讨论】:

    标签: css transform


    【解决方案1】:

    我找到了使用绝对定位的解决方法。旋转的文本可以绝对定位“相对于其最近定位的祖先的边界”。说明:

    • position: relative 在容器上使其成为“最接近的祖先”
    • position: absolute 在旋转文本上,设置为容器底部(减去行高)
    • 从左上角旋转文本

    JSFiddle

    .container {
      position: relative; /*make container the closest positioned ancestor*/
      border: 1px solid red;
      display: inline-block;
      height: 400px;
      min-width: 30px; /*same as line-height of rotated text*/
    }
    
    .rotate {
      text-align: center;
      overflow: hidden;
      height: 30px;
      line-height: 30px;
      width: 400px; /*matches the height of the container*/
      position: absolute;
      bottom: -32px; /*0 = bottom of container, then subtract (line-height+border)*/
      border: 1px solid blue;
      transform: rotate(-90deg);
      transform-origin: top left;
    }
    

    假设:

    • 可以将文本宽度设置为合理的值(例如容器的高度)
    • 文本中没有换行符(单行解决方案)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-05-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-02
      相关资源
      最近更新 更多