Search code examples
htmlcssflexboxvertical-alignmentcss-transforms

How can I vertically center rotated text using Flexbox layout?


How can I vertically center rotated text using flexbox layout? I want something that looks like this:

enter image description here

Here's what I have so far:

html, body { height: 100%; }
body { background-color: #efefef; }

body > div {
  align-content: center;
  background-color: white;
  border: 1px solid black;
  display: flex;
  height: 100%;
  width: 25px;
}

body > div > div {
  flex: 1;
  transform: rotate(-90deg);
}
<div>
  <div>
    Where did I go?
  </div>
</div>


Solution

  • Add white-space: nowrap and center horizontally and vertically using:

    align-items: center;
    justify-content: center;
    

    (and you don't need the flex: 1!)

    Also removed the browser margin and added in box-sizing: border-box to add the finishing touches.

    See demo below:

    * {
      box-sizing: border-box;
    }
    html,
    body {
      height: 100%;
      margin: 0;
    }
    body {
      background-color: #efefef;
    }
    body > div {
      background-color: white;
      border: 1px solid black;
      display: flex;
      height: 100%;
      width: 25px;
      align-items: center;
      white-space: nowrap;
      justify-content: center;
    }
    body > div > div {
      transform: rotate(-90deg);
    }
    <div>
      <div>
        Where did I go?
      </div>
    </div>