微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

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

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

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

In the HTML namespace,the transform property does not affect the flow of the content surrounding the transformed element.

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

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

解决方法

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

>位置:相对于容器使其成为“最接近的祖先”
> position:旋转文本的绝对值,设置为容器的底部(减去行高)
>从左上角旋转文本

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;
}

假设:

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

原文地址:https://www.jb51.cc/css/242395.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。