html - 将一项 flex 元素从 flex 容器中移出

标签 html css flexbox

我遇到这种情况,我必须使 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:absoluteheight: 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/

相关文章:

html - 如何在嵌套列中将行底部对齐?

html - 柔性网格未对齐

html - 如何在虚线边框内水平和垂直居中文本

html - 如何在水平滚动中设置全宽div

html - 手机上的网格布局问题

html - 100% 缩放时看起来不错,但当我缩小时,一切都错了

html - 调整浏览器窗口大小时,CSS 背景颜色宽度会减小

javascript - "Uncaught TypeError: this.setValues is not a function"使用 Google map API v3

jquery - FullCalendar - 未设置事件时添加不可用并设置背景色

html - 在容器中心画线,而不是屏幕?