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

溢出的柔性容器的子级超过容器[副本]

  •  3
  • Kevin  · 技术社区  · 6 年前

    我在这方面已经做了一段时间了,尝试了很多我在不同stackoverflow问题/blogposts/中看到的解决方案。但我真的不知道出了什么问题。

    我有一个弯曲的二级舱,里面有两个二级舱。顶部的分区A具有固定高度,其他分区B使用 flex: 1; . 如果屏幕调整了大小,并且它小于A+B的高度,那么B将开始溢出。我希望它滚动,但我也希望内容在滚动时完全可见。由于某些原因,我无法理解,内容呈现在DIV B的顶部,正如您在下面的屏幕截图中看到的 my fiddle :

    enter image description here

    以前问过的一些问题让我有了一些收获。例如,将主体设置为 height: auto; 但是当我的屏幕大于A+B时,就不能再对中了。 min-height: 0; 在这种情况下似乎也无济于事。

    我如何确保我的容器溢出,但将充分显示它的内容?

    1 回复  |  直到 6 年前
        1
  •  1
  •   tao    6 年前

    你可以通过给予 .second :

    flex-basis: auto;
    flex-shrink: 0;
    

    或者,用速记法: flex: 1 0 auto;

    工作示例:

    html, body {
      width: 100%;
      height: 100%;
      padding: 0;
      margin: 0;
    }
    
    body {
      display: flex;
      flex-direction: column;
    }
    
    .second {
      flex: 1 0 auto;
      background: blue;
      width: 100%;
      
      display: flex;
      justify-content: center;
      align-items: center;
      
      min-height: 0;
      
      overflow: auto;
    }
    
    .container {
      display: flex;
      flex-direction: column;
      width: 100%;
      max-width: 500px;
      min-height: 0;
      /* added this to make it obvious. Obviously, not needed */
      padding: 2rem 0;
    }
    
    .container-child {
      height: 110px;
      background: green;
      width: 100%;
    }
    
    .container-child:not(:last-child) {
      margin-bottom: 30px;
    }
    <div class="second">
      <div class="container">
        <div class="container-child"></div>
        <div class="container-child"></div>
        <div class="container-child"></div>
      </div>
    </div>

    我加了一些上下衬垫 .container 使它明显地起作用 -但不需要。

    现在让我们看看 为什么? 这正在发生。当你申请 .second { flex:1; } 它的意思是:

    flex-grow: 1;
    flex-shrink: 1;
    flex-basis: 0%;
    

    …这使得它的大小比其内容物小。

    每当有一个较大的子级以较小的父级为中心时,浏览器将不提供滚动条 top (或) left ,当水平时),因为如果父级和子级的顶部重合并且子级大于父级,则子级不再居中,是吗? 同样的情况也发生在使用其他中心技术时,而您将一个较大的孩子放在一个较小的家长中。
    为了解决这个问题,你需要防止孩子的成长超过父母。

    在这种情况下,它意味着尺寸 第二 基于其内容( flex-basis: auto )不让它收缩:( flex-shrink: 0; )

    为了更好地可视化问题,请考虑以下示例:

    .left, .right {
      position: relative;
      border: 1px solid red;
      padding: 1rem 5rem;
    }
    .left {
      left: -5rem;
    }
    .right {
      right: -5rem;
    }
    <div class="left">
      I'm taken left
    </div>
    <div class="right">
      I'm taken right
    </div>

    如果浏览器提供了滚动条,允许您滚动到 .left ,这意味着 left: -5rem 不适用。我希望这是有道理的,我不能解释得更好。