Rotate the text and squeeze its container to a new width

I want to rotate some text for vertical display (y-axis chart label). The text can have any variable length (but always on the same line).

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

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

However, the original width and height of the element are preserved even after rotation, as described in the specification :

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

This means that the width of the element container expands depending on the length of the label text, affecting the position of the adjacent chart.

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

+5
source share
1 answer

I found a workaround using absolute positioning. Rotating text can be absolutely positioned โ€œrelative to the border of its nearest located ancestorโ€. Explanation:

  • position: relative on the container to make it the "closest positioned ancestor"
  • position: absolute on the rotated text, set the bottom of the container (minus the line height)
  • rotate text in upper 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; } 

Assumptions:

  • that the width of the text can be set to a reasonable value (for example, the height of the container).
  • no lines in the text (single line solution)
+5
source

Source: https://habr.com/ru/post/1214235/


All Articles