【问题标题】:Making children of flex item not grow beyond the flex item使弹性项目的孩子不会超出弹性项目
【发布时间】:2018-08-20 17:09:25
【问题描述】:

我得到了一个页面布局,其中包含一个 flex 容器(具有列方向)和一个 flex 设置为 1 的 flex 项。我需要将我的元素添加到这个 flex 项中。我希望将容器的高度固定为 flex 项 div 的 100% - 但问题是我的根容器的高度是动态的并且可以不断增长,并且 flex 项的高度随着我的根容器的高度而不断增长。

我不想在容器上设置高度 - 无论如何我可以限制容器的高度。

这是我正在查看的内容的简化版本。 flex-container 和 flex-items 已经给我了。 test-element 是我需要放入页面的 div,我需要限制 test-element 的高度以适应 100% 的弹性项目。

.flex-container {
  display: flex;
  width: 120px;
  height: 120px;
  background-color: pink;
  flex-direction: column;
}

.flex-item {
  background-color: yellow;
  flex: 1;
}

.flex-item.second {
  background-color: blue;
  flex: 0;
}

.test-element {
  background-color: green;
  flex-grow: 1;
  height: 150px;
  // doens't help
  overflow: hidden;
}
<div class="flex-container">
  <div class="flex-item first">
    <div class="test-element"></div>
  </div>
  <div class="flex-item second"></div>
</div>

【问题讨论】:

    标签: html css flexbox


    【解决方案1】:

    不像你那样在.test-element上设置一个固定的高度:

    .test-element {
      background-color: green;
      flex-grow: 1;
      height: 150px;
      overflow: hidden;
    }
    

    使父级 (.flex-item.first) 成为弹性容器。这将自动将align-items: stretch 应用到子级(.test-element),使其扩展容器的整个高度。无需固定高度。

    .flex-container {
      display: flex;
      flex-direction: column;
      width: 120px;
      height: 120px;
      background-color: pink;
    }
    
    .flex-item {
      flex: 1;
      display: flex;   /* new; flex-direction: row, by default */
      background-color: yellow;
    }
    
    .test-element {
      flex-grow: 1;
      background-color: green;
    }
    
    .flex-item.second {
      flex: 0;
      background-color: blue;
    }
    <div class="flex-container">
      <div class="flex-item first">
        <div class="test-element"></div>
      </div>
      <div class="flex-item second"></div>
    </div>

    【讨论】:

      猜你喜欢
      • 2016-08-27
      • 2014-08-09
      • 2020-04-20
      • 2021-11-20
      • 2016-08-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多