防止项目缩小

Prevent item from shrinking

我想制作一个高度可变的简单弹出窗口,如果它小于视口,它将垂直居中,并且当它大于视口时不会缩小。这是示例代码:

.flex-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
}
.flex-child {
  flex-shrink: 0;
}
.item {
  height: 160px;
  background-color: #C3C3FC;
  border: 1px solid red;
}
<div class="flex-container">
  <div class="flex-child">
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
  </div>
</div>

请注意,flex 容器上的 height: 100% 被忽略,因为其包含块 (body) 具有 height: auto.

因此,flex 容器的高度将是其内容的高度,因此 justify-content: center 不会引人注意。

要修复它,你可以添加一个固定高度到body:

html, body {
  height: 100%;
  margin: 0;
}

但是,如果内容比视口高,结果将是不理想的,因为你有justify-content: center,内容会从上方和下方溢出,但滚动条不允许看到上面的溢出。

所以你不应该为 flex 容器使用固定高度,你只需要一个最小高度,这样它就可以在必要时增长:

.flex-container {
  min-height: 100%;
  height: auto; /* Initial value */
}

html, body {
  height: 100%;
  margin: 0;
}
.flex-container {
  min-height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
}
.flex-child {
  flex-shrink: 0;
}
.item {
  height: 160px;
  background-color: #C3C3FC;
  border: 1px solid red;
}
<div class="flex-container">
  <div class="flex-child">
    <div class="item">
    </div>
    <div class="item">
    </div>
    <div class="item">
    </div>
    <div class="item">
    </div>
  </div>
</div>