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).
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:
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.
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
on container to make it the "closest positioned ancestor"position: absolute
on rotated text, set to bottom of container (minus line height)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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With