Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rotate text and shrink its container to the new width

Tags:

css

transform

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.

like image 805
mtmacdonald Avatar asked Feb 26 '15 11:02

mtmacdonald


Video Answer


1 Answers

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

Assumptions:

  • that text width can be set to a sensible value (e.g. height of container)
  • no line breaks in text (single-line solution)
like image 143
mtmacdonald Avatar answered Sep 30 '22 18:09

mtmacdonald