旋转文本并将其容器缩小到新的宽度 [英] Rotate text and shrink its container to the new width

查看:86
本文介绍了旋转文本并将其容器缩小到新的宽度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to rotate some text for vertical display (a y-axis chart label). The text can be of any variable length (but is always on one line).

我尝试使用 CSS3转换(请参见 JSFiddle ):

I've tried to rotate using CSS3 transforms (see JSFiddle):

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

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

However, the element's original width and height is retained even after rotation, as described in the spec:

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

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

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

Which means that the element's container width expands depending the label text length, affecting the position of the adjacent chart.

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

How do I rotate text and shrink its container to the new width? Any solution will be helpful, including JavaScript/jQuery solutions, or alternative approaches.

推荐答案

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

I found a workaround using absolute positioning. The rotated text can be absolutely positioned "relative to the border of its closest positioned ancestor". Explanation:

  • position: relative放置在容器上,使其成为最近的祖先"
  • position: absolute旋转文本,设置为容器的底部(减去行高)
  • 从左上角旋转文本
  • position: relative on container to make it the "closest positioned ancestor"
  • position: absolute on rotated text, set to bottom of container (minus line height)
  • rotate the text from the top-left corner

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

假设:

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

这篇关于旋转文本并将其容器缩小到新的宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆