旋转文本并将其容器缩小到新宽度

mtm*_*ald 11 css transform css3

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

我试图使用CSS3转换旋转(参见JSFiddle):

.rotate {
   transform: rotate(270deg);
}
Run Code Online (Sandbox Code Playgroud)

但是,即使在旋转之后,元素的原始宽度和高度也会保留,如规范中所述:

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

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

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

mtm*_*ald 10

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

  • 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;
}
Run Code Online (Sandbox Code Playgroud)

假设:

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