使弹性项目的子项不会超出弹性项目

Arv*_*man 5 html css flexbox

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

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

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

.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;
}
Run Code Online (Sandbox Code Playgroud)
<div class="flex-container">
  <div class="flex-item first">
    <div class="test-element"></div>
  </div>
  <div class="flex-item second"></div>
</div>
Run Code Online (Sandbox Code Playgroud)

Mic*_*l_B 4

而不是像您一样在 上设置固定高度.test-element

.test-element {
  background-color: green;
  flex-grow: 1;
  height: 150px;
  overflow: hidden;
}
Run Code Online (Sandbox Code Playgroud)

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

.test-element {
  background-color: green;
  flex-grow: 1;
  height: 150px;
  overflow: hidden;
}
Run Code Online (Sandbox Code Playgroud)
.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;
}
Run Code Online (Sandbox Code Playgroud)