如果我有一个包含多个容器的flexbox容器,我该如何制作容器'包含的项目在容器本身之前换行?
例如(codepen):
HTML
<div>
<row>
<column id="first">
<widget width=1 height=8></widget>
<widget width=1 height=8></widget>
</column>
<row id="second">
<widget></widget>
<widget></widget>
<widget></widget>
</row>
</row>
</div>
CSS
column, row, widget {
background: RGBA(0,0,0,.2);
margin: 1em;
display: flex;
flex-wrap: wrap;
align-items: top;
align-content: flex-start;
}
row {
flex-direction: row;
}
column {
flex-direction: column;
}
widget {
min-height: 100px;
flex-grow: 2;
flex-shrink: 1;
width: calc(25% - 3em);
min-width: 300px;
height: 100px;
flex-basis: 0;
padding: .5em;
display: block;
}
widget[width=1] {
flex-grow: 1;
min-width: 150px;
}
widget[width=4] {
flex-grow: 4;
min-width: 600px;
}
widget[width=8] {
flex-grow: 8;
min-width: 1200px;
}
widget[height=1] {
min-height: 150px;
}
widget[height=4] {
min-height: 600px;
}
widget[height=8] {
min-height: 1200px;
}
widget {
background: RGBA(200,0,20,.5);
}
我希望#second
中的项目在#second
本身包裹在#first
之后包裹。换句话说,我总是想在尝试包装最外面的项目之前尝试包装最里面的项目,这似乎与默认情况下的情况相反。有没有办法做到这一点?
编辑:有视觉澄清请求。
所需行为,略小一些。最内层的物品在它们的容器之前包裹。
期望的行为,更小。
期望的行为,最小的。在最里面的物品不能再包裹之后,容器最终会包裹。
实际发生的事情:容器在其内容之前包裹。
答案 0 :(得分:6)
我不相信有任何灵活属性可以简化这个过程。但是,flexbox规范确实允许absolutely-positioned flex children。因此,通过媒体查询和绝对定位的组合,可以在容器本身包装之前使容器内的flex项目进行换行。
试试这个:
HTML (无更改)
CSS (添加媒体查询和绝对定位)
#second { position: relative; }
/* establishes nearest positioned ancestor for absolute positioning */
@media screen and (max-width: 1000px) {
#second widget:nth-child(3) {
position: absolute;
left: 0;
bottom: 0;
width: 90%; }
}
@media screen and (max-width: 800px) {
#second { height: 375px; }
#second widget:nth-child(2) {
position: absolute;
left: 0;
bottom: 127px;
width: 75%; }
#second widget:nth-child(3) {
position: absolute;
left: 0;
bottom: 0;
width: 75%; }
}
/* final media query removes absolute positioning and restores flex properties */
@media screen and (max-width: 600px) {
column, row, widget { flex-wrap: wrap; }
#second widget {
position: static;
width: calc(25% - 3em);
min-width: 300px;
}
请注意,尽管此代码执行的问题是 - 它在容器本身包装之前将Flex项目包装在其容器中 - 它只是意味着传达解决方案的基本概念。我认为超出此问题范围的弹性项目的边距和宽度等问题可能仍需要解决。