我想使用CSS Flexbox属性来制作某种网格,其中元素可能跨越多行.
这是基本的HTML源代码:
<section class="group">
<h1>...</h1>
<section class="item">...</section>
<section class="item">...</section>
<section class="item">...</section>
<section class="item">...</section>
<section class="item">...</section>
<section class="item">...</section>
</section>
Run Code Online (Sandbox Code Playgroud)
这就是我想要实现的目标:

在内部section.group,我希望它h1是100%宽,每个section.item都是50%宽,排列在n ×2网格中,其中n取决于内部的数量sections,这可能会改变.
我无法改变HTML,这意味着我无法section.item使用unsemantic 来包装divs.我只能使用CSS.这是我到目前为止所拥有的:
.group {
display: flex;
}
.group h1 {}
.group .item {}
Run Code Online (Sandbox Code Playgroud)
(开始不多)
如何使用Flexbox模块实现此目的?
首先,确保flex-direction设置为row或row-reverse,因为我们想要水平布局项目(从左到右或从右到左).但实际上,这flex-direction: row;是默认的,所以我们并不明确需要它.它只适合初学者.
然后,为了确保框在多个轨道上突破,请添加 flex-wrap: wrap;.
.group {
display: flex;
flex-direction: row;
flex-wrap: wrap;
}
Run Code Online (Sandbox Code Playgroud)
现在我们必须调整项目的大小.TLDR:
.group h1 { flex: 100%; } /* flex: 1 1 100%; */
.group .item { flex: 50%; } /* flex: 1 1 50%; */
Run Code Online (Sandbox Code Playgroud)
如果您想知道原因,请继续阅读.否则就是这样!
默认情况下,每个弹性项的主要大小(在本例中为水平大小或宽度)将延迟到其width属性的指定值.乍一看,我们可能只想声明宽度:
/* NOPE!
.group h1 { width: 100%; }
.group .item { width: 50%; }
*/
Run Code Online (Sandbox Code Playgroud)
然而,这不是非常适合未来的,因为我们可能希望稍后改变弹性方向,例如我们以垂直书写模式编写,或者即使我们只想交换布局.如果flex-direction是column或column-reverse,那么设置宽度将不会得到我们想要的.我们真的希望确定尺寸的大小,这就是flex它的用途.
(这是一个非常基本的用法flex,但它实际上更多......唉...... 灵活 ......阅读更多关于MDN上的flex速记属性.)
还有一些关于CSS3规范和MDN指南中的flexbox的信息.