小编典典

在高度未知的情况下使用flexbox垂直居中的问题

css

我的布局有一个容器flex-container和一个孩子。

HTML:

<div class="flex-container">
  <div>text</div>
</div>

容器和孩子的身高未知。目标是:

如果孩子的身高低于容器,则其水平和垂直居中。
如果孩子的身高大于容器,则它会调整到顶部和底部,我们可以滚动。
方案: 在此处输入图片说明

使用flexbox将元素居中的最快方法是:

.flex-container

{

  display: flex;

  align-items: center; /* vertical */

  justify-content: center; /* horizontal */



  width: 100%;

  height: 300px; /* for example purposes */

  overflow-y: scroll;

  background: #2a4;

}



.flex-container > div

{

  background: #E77E23;

  width: 400px;

}


<div class="flex-container">

  <div>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Iure fugit voluptas eius nemo similique aperiam quis ut! Ipsa aspernatur rem nesciunt est sed hic culpa nisi delectus error explicabo reprehenderit. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Iure fugit voluptas eius nemo similique aperiam quis ut! Ipsa aspernatur rem nesciunt est sed hic culpa nisi delectus error explicabo reprehenderit. </div>

</div>

但是,如果容器的子代具有更高的高度,则该子代将无法
正确显示。子项显示为割伤(仅顶部)。

html,body

{

  height: 100%;

  width: 100%;

  padding: 0;

  margin: 0;

}



.flex-container

{

  display: flex;

  align-items: center; // vertical

  justify-content: center; // horizontal



  width: 100%;

  height: 100px;

  overflow-y: scroll;

  background: #2a4;

}



.flex-container > div

{

  background: #E77E23;

  width: 400px;

}


<div class="flex-container">

  <div>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Iure fugit voluptas eius nemo similique aperiam quis ut! Ipsa aspernatur rem nesciunt est sed hic culpa nisi delectus error explicabo reprehenderit. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Iure fugit voluptas eius nemo similique aperiam quis ut! Ipsa aspernatur rem nesciunt est sed hic culpa nisi delectus error explicabo reprehenderit. </div>

</div>

阅读 323

收藏
2020-05-16

共1个答案

小编典典

I found the solution:

.flex-container
{
  display: flex; /* only */
  overflow-y: scroll;
}

.flex-container > div
{
  margin: auto; /* horizontal and vertical align */
}



html,body

{

  height: 100%;

  width: 100%;

  padding: 0;

  margin: 0;

}



.flex-container

{

  display: flex;

  width: 100%;

  height: 100px; /* change height to 300px */

  overflow-y: scroll;

  background: #2a4;

}



.flex-container > div

{

  padding: 1em 1.5em;

  margin: auto;

  background: #E77E23;

  width: 400px;

}


<div class="flex-container">

  <div>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Iure fugit voluptas eius nemo similique aperiam quis ut! Ipsa aspernatur rem nesciunt est sed hic culpa nisi delectus error explicabo reprehenderit. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Iure fugit voluptas eius nemo similique aperiam quis ut! Ipsa aspernatur rem nesciunt est sed hic culpa nisi delectus error explicabo reprehenderit. </div>

</div>
2020-05-16