如何使用Flexbox布局垂直居中旋转文本?

时间:2016-12-08 17:38:08

标签: html css flexbox vertical-alignment css-transforms

如何使用flexbox布局垂直居中旋转文本?我想要一些看起来像这样的东西:

enter image description here

这是我到目前为止所拥有的:

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>

2 个答案:

答案 0 :(得分:5)

添加white-space: nowrap并使用以下方式水平和垂直居中

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

(你不需要flex: 1!)

同时删除浏览器边距并添加到box-sizing: border-box以添加最后润色。

见下面的演示:

* {
  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>

答案 1 :(得分:2)

您可以通过更改代码中的一些内容来实现此目的:

  1. 为您的文字white-space: nowrap;
  2. 为您的包含div justify-content: center;
  3. 在您的包含div中,将align-content更改为align-items
  4. &#13;
    &#13;
    html, body { height: 100%; }
    body { background-color: #efefef; }
    
    body > div {
      align-items: center;
      justify-content: center;
      background-color: white;
      border: 1px solid black;
      display: flex;
      height: 100%;
      width: 25px;
    }
    
    body > div > div {
      white-space: nowrap;
      transform: rotate(-90deg);
    }
    &#13;
    <div>
      <div>
        Where did I go?
      </div>
    </div>
    &#13;
    &#13;
    &#13;

    *注意您也可以从内部div中移除flex: 1;,因为它没有做任何事情。

相关问题