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:
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?
First, make sure flex-direction
is set to row
or row-reverse
, because we want to lay out the items horizontally (left-to-right or right-to-left). But really, flex-direction: row;
is default so we don’t explicitly need it. It’s just here for beginners.
Then, to ensure the boxes break across multiple tracks, add flex-wrap: wrap;
.
.group {
display: flex;
flex-direction: row;
flex-wrap: wrap;
}
Now we have to size the items. TLDR:
.group h1 { flex: 100%; } /* flex: 1 1 100%; */
.group .item { flex: 50%; } /* flex: 1 1 50%; */
If you want to know why, read on. Otherwise, that’s it!
By default, the main size (in this case, horizontal size, or width) of each flex item defers to the specified value of its width
property. At first glance, we may want to just declare the widths:
/* NOPE!
.group h1 { width: 100%; }
.group .item { width: 50%; }
*/
However this is not very future-proof, as we may want to later change the flex-direction if for example we are writing in a vertical writing mode, or even if we merely want to swap the layout. If flex-direction
is column
or column-reverse
, then setting the widths won’t get us what we want. We are really looking to size the main-size, which is what flex
is for.
(This is an extremely basic usage of flex
, but it is in fact a lot more …ahem… flexible …. Read more about the flex
shorthand property on MDN.)
And some more info about flexbox in the CSS3 specs and in the MDN guide.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With