Rotate text and shrink its container to the new width

前端 未结 1 1635
孤独总比滥情好
孤独总比滥情好 2021-01-11 11:27

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 usi

相关标签:
1条回答
  • 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)
    0 讨论(0)
提交回复
热议问题