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

时间:2015-02-26 11:43:19

标签: css css3 transform

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

我尝试使用 CSS3转换进行轮播(请参阅JSFiddle):

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

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

  

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

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

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

1 个答案:

答案 0 :(得分:9)

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

    容器上的
  • 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;
}

假设:

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