我遇到这种情况,我必须使 flex 容器中的 flex 元素之一占据父级( flex 容器)的所有可用空间。因此,我通过将位置设置为“绝对”将其他 flex 元素移出 DOM。
<div style="display:flex; flex-direction:column">
<div style="flex:1 1 auto">Flex Item which should take it all...</div>
<div style="position:absolute">Not really a Flex Item 1</div>
<div style="position:absolute">Not really a Flex Item 1</div>
<div style="position:absolute">Not really a Flex Item 2</div>
</div>
上面的稍微不那么hacky的版本:
<div style="display:flex; flex-direction:column">
<div style="flex:1 1 auto">Flex Item which should take it all...</div>
<div style="position:absolute">
<div>Not really a Flex Item 1</div>
<div>Not really a Flex Item 1</div>
<div>Not really a Flex Item 2</div>
</div>
</div>
约束:
- 我无法对那些不需要的 flex 元素使用
display:none
。它们实际上是弹出窗口,默认情况下不可见,但稍后在某些用户操作中变为可见。 - 由于某些其他原因,我无法将这些 flex 元素移出 flex 容器。
是否有比使用 position:absolute
更简洁、更优雅的解决方案(可能是基于 Flexbox 的解决方案?),同时考虑到上述约束?
最佳答案
您也可以反过来做:让所有其他元素仍然是 flex 元素,并使该元素 position:absolute
的 height: 100%, width: 100 %
(您必须将 position:relative
添加到容器元素才能使其工作)
.x {
background: red;
position: relative;
}
.y {
background: green;
position: absolute;
width: 100%;
height: 100%;
}
<div style="display:flex; flex-direction:column" class="x">
<div style="flex:1 1 auto" class="y">Flex Item which should take it all...</div>
<div>Not really a Flex Item 1</div>
<div>Not really a Flex Item 1</div>
<div>Not really a Flex Item 2</div>
</div>
关于html - 将一项 flex 元素从 flex 容器中移出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46517650/