Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make Flexbox span multiple lines?

Tags:

css

flexbox

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.items with unsemantic divs. 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?

like image 698
chharvey Avatar asked Jul 31 '14 04:07

chharvey


1 Answers

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.

like image 88
chharvey Avatar answered Sep 22 '22 17:09

chharvey