使 flex 项的子元素不要超出 flex 项的大小增长

5
我被给予了一个页面布局,其中包含一个列方向的 flex 容器和一个 flex 项目,其 flex 属性设置为 1。我需要将我的元素添加到这个 flex 项目中。我希望将我的容器高度固定在 flex 项目 div 的 100% - 但问题在于我的根容器的高度是动态的,并且可以继续增长,flex 项目的高度也会随着根容器的高度增长而增长。
我不想在我的容器上设置高度 - 是否有任何方法可以限制容器的高度。
以下是我所看到的大大简化版本。flex-container 和 flex-items 已经预先给出。test-element 是我需要放入页面并限制其高度以适应 flex-item 的 100% 的 div。

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

1个回答

4

不要像你现在这样给 .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>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接