How can I vertically center rotated text using Flexbox layout?

独自空忆成欢 提交于 2021-02-19 05:05:21

问题


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

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>

回答1:


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>



回答2:


You can accomplish this by changing a couple things in your code:

  1. Give your text a white-space: nowrap;.
  2. Give your containing div a justify-content: center;.
  3. In your containing div, change align-content to align-items.

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);
}
<div>
  <div>
    Where did I go?
  </div>
</div>

*Note You can also remove flex: 1; from your inner div, as it is not doing anything.



来源:https://stackoverflow.com/questions/41045537/how-can-i-vertically-center-rotated-text-using-flexbox-layout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!