首页 > 解决方案 > 居中的内容是从具有固定高度和滚动条的父级中剪切出来的

问题描述

我有一个具有溢出-y 和固定高度的父级。我希望居中对齐它的孩子。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>

标签: htmlcssflexboxcentering

解决方案


对齐将在flexbox的flex 轴上工作。因此,您可以切换到列 flexbox并为元素提供(覆盖flex item的默认设置)- 请参见下面的演示:min-height: 0min-width: autochild

.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>


推荐阅读