chharvey chharvey - 4 months ago 17
CSS Question

How to make Flexbox span multiple lines?

I would like to use CSS Flexbox properties to make some sort of grid, where the elements may span across multiple lines.

Here's the essential HTML source code:

<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>


Here's what I want to achieve:

enter image description here

Within the
section.group
, I want the
h1
to be 100% wide with each
section.item
being 50% wide, arranged in a n × 2 grid, where n is dependent on the number of inner
sections
, which may change.

I cannot change the HTML, which means I cannot wrap
section.item
s with unsemantic
div
s. I can only use CSS. Here's what I have so far:

.group {
display: flex;
}
.group h1 {}
.group .item {}


(not much of a start)

How can I use the Flexbox Module to achieve this?

Answer

To ensure the boxes break across multiple lines, add flex-wrap: wrap; to .group {}.

.group {
    display: flex;
    flex-wrap: wrap;
}
.group h1 {
    flex: 100%; /* flex: 1 1 100%; */
}
.group .item {
    flex: 50%;  /* flex: 1 1  50%; */
}

The flex property is shorthand for flex-grow, flex-shrink, and flex-basis, in that order. If only one or two values are given, the value(s) omitted compute to 1, 1, or auto, respectively. The initial value of flex is 0 1 auto—the initial values of each respective property.

Read more about these properties in the CSS3 specs and in the MDN guide.

Comments