仅当屏幕高度足够时,Flexbox垂直居中

时间:2020-03-02 14:42:56

标签: css flexbox

我使用flexbox方法将垂直元素居中,但是如果屏幕高度不足以在中心模式下显示整个元素,则需要使用滚动选项将其从顶部对齐。

flexbox是否有可能做到这一点?

非常感谢!

:'<,'>s/something/other/
.flex {
  display: flex;
  justify-content: center;
  align-items: center;
  background: red;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

.flex>div {
  background: green;
  padding: 5vw;
  width: 50vw;
}

2 个答案:

答案 0 :(得分:2)

您可以使用bottom: 0至少填充整个屏幕高度,而不必使用min-height: 100vh;填充整个屏幕高度,但是如果出现以下情况,请保持打开状态以展开:含量更高。

.flex {
  display: flex;
  justify-content: center;
  align-items: center;
  background: red;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  min-height: 100vh;
}

.flex>div {
  background: green;
  padding: 5vw;
  width: 50vw;
}
<div class="flex">
  <div>
    <p>Lorem ipsum dolor Lorem ipsum dolorLorem ipsum dolorLorem ipsum dolorLorem ipsum dolorLorem ipsum dolorLorem ipsum dolorLorem ipsum dolorLorem ipsum dolorLorem ipsum dolorLorem ipsum dolorLorem ipsum dolorLorem ipsum dolor Lorem ipsum dolor Lorem
      ipsum dolorLorem ipsum dolorLorem ipsum dolorLorem ipsum dolorLorem ipsum dolorLorem ipsum dolorLorem ipsum dolorLorem ipsum dolorLorem ipsum dolorLorem ipsum dolorLorem ipsum dolorLorem ipsum dolor Lorem<br><br><br> ipsum dolor Lorem ipsum dolorLorem
      ipsum dolorLorem ipsum dolorLorem ipsum dolorLorem ipsum dolorLorem ipsum dolorLorem ipsum dolorLorem ipsum dolorLorem ipsum dolorLorem ipsum dolorLorem ipsum dolorLorem ipsum dolor Lorem ipsum dolor Lorem ipsum dolorLorem ipsum dolorLorem ipsum
      dolorLorem ipsum dolorLorem ipsum dolorLorem ipsum dolorLorem ipsum dolorLorem ipsum dolorLorem ipsum dolorLorem ipsum dolorLorem ipsum dolorLorem ipsum dolor</p>
  </div>
</div>

答案 1 :(得分:0)

删除flex类中的绝对位置。这应该足够了。

.flex{display: flex; justify-content: center; align-items: center; background: red;}
.flex>div{background: green; padding: 5vw; width: 50vw;}
<div class="flex">
  <div>
    <p>Lorem ipsum dolor Lorem ipsum dolorLorem ipsum dolorLorem ipsum dolorLorem ipsum dolorLorem ipsum dolorLorem ipsum dolorLorem ipsum dolorLorem ipsum dolorLorem ipsum dolorLorem ipsum dolorLorem ipsum dolorLorem ipsum dolor Lorem ipsum dolor Lorem ipsum dolorLorem ipsum dolorLorem ipsum dolorLorem ipsum dolorLorem ipsum dolorLorem ipsum dolorLorem ipsum dolorLorem ipsum dolorLorem ipsum dolorLorem ipsum dolorLorem ipsum dolorLorem ipsum dolor Lorem<br><br><br> ipsum dolor Lorem ipsum dolorLorem ipsum dolorLorem ipsum dolorLorem ipsum dolorLorem ipsum dolorLorem ipsum dolorLorem ipsum dolorLorem ipsum dolorLorem ipsum dolorLorem ipsum dolorLorem ipsum dolorLorem ipsum dolor Lorem ipsum dolor Lorem ipsum dolorLorem ipsum dolorLorem ipsum dolorLorem ipsum dolorLorem ipsum dolorLorem ipsum dolorLorem ipsum dolorLorem ipsum dolorLorem ipsum dolorLorem ipsum dolorLorem ipsum dolorLorem ipsum dolor</p>
  </div>
</div>