以固定高度和滚动条从 parent 中切出居中内容

Centered content is cut out of parent with fixed height and scrollbar

我有一个 parent overflow-y 和固定高度 。我希望 居中对齐它的 childchild 的内容可能大小不一 ,有时 会溢出 parent 并触发滚动条。在这些情况下,child 的顶部和底部 内容被删除

我希望 child 居中对齐,但前提是它小于 parent。或者它可以始终居中对齐,但是 内容不应该被剪切掉

在这里查看问题:https://jsfiddle.net/gumy023z/

.parent {
  background-color: red;
  height: 40px;
  overflow-y: scroll;
  
  /* Comment out the flex, and all the content will be available */
  display: flex;
  justify-content: center;
  align-items: center;
}
<div class="parent">
  <div class="child">
    This is a test <br> This is a test <br> This is a test
  </div>
</div>

对齐[=29​​=] 将在 flexboxflex 轴 中工作。因此,您可以切换到 列 flexbox 并提供 min-height: 0 覆盖 默认 min-width: auto 设置 [= child 元素的 23=]flex item) - 请参阅下面的演示:

.parent {
  background-color: red;
  height: 40px;
  overflow-y: auto;
  display: flex;
  flex-direction: column; /* ADDED */
  justify-content: center;
  align-items: center;
}

.child {
  min-height: 0; /* ADDED */
}
<div class="parent">
  <div class="child">
    1. This is a test <br> 2. This is a test <br> 3. This is a test
  </div>
</div>