代码之家  ›  专栏  ›  技术社区  ›  arbuthnott

子元素垂直居中,但允许父元素在子元素溢出时展开

  •  2
  • arbuthnott  · 技术社区  · 8 年前

    我正在寻找这个问题的css唯一解决方案。我有一个家长和一个孩子。家长有一个最小的身高。当子div的高度较小时,我希望它在父div中垂直居中。但当子div展开超过父div的最小高度时,我希望父div展开。

    如图所示: enter image description here

    我可以接近; position: relative 在孩子身上,我可以在定位孩子的同时影响父母的身高,但我不知道如何确定正确的位置( top: 50% transform: translateY 不会对我起作用,因为父母的身高不固定)。

    这件事把我难住了!提前感谢您的建议。

    1 回复  |  直到 8 年前
        1
  •  3
  •   Temani Afif    8 年前

    使用flex可以轻松做到这一点:

    .container {
      min-height: 300px;
      display: flex;
      background: red;
      justify-content: center; /* Center horizontally */
    }
    
    .container>div {
      height: 200px;
      width: 200px;
      background: blue;
      margin: auto; /* Center vertically */
    }
    <div class="container">
      <div>some content</div>
    </div>

    内容高度越大:

    .container {
      min-height: 300px;
      display: flex;
      background: red;
      justify-content: center;
    }
    
    .container>div {
      height: 800px;
      width: 200px;
      background: blue;
      margin: auto;
    }
    <div class=“容器”>
    <div>部分内容</div>
    </div>