Reskk Reskk - 2 months ago 12
CSS Question

Flexbox - wrapping items in sets of 2

Got a quick question for anyone familiar with Flexbox.

I have a row of 4 flex items. I'm looking to make it so at the first breakpoint (

max-width:1024px
) they wrap into 2 columns of 2. I thought I might be able to achieve this using a % value on the width of each item inside the flex container but that doesn't seem to work.

The code is here:

http://codepen.io/reskk/pen/rrpdVm

I'm thinking I could achieve this by wrapping the flex items 2 at a time within 2
<div>
s. However this just creates a lot more work to do with layout and making the page symmetrical.

Is there a way I can do this just using width percentages or something similar?

For example:

25% baseline width - 4 per row

50% width @ 1024px - 2 per row

100% width @ 769px - 1 per row

Thanks,

Rik

Answer

To achieve that, you need to wrap your flex container and set flex-grow & shrink to 0% to children in order to prevent your flex items from (obviously) stretching or shrinking when their content doesn't fit in the desired space (i.e. 25%). Then, you can set flex-basis normally for each breakpoint.

Based on your example, here's what you can do:

.whatflex {
  display: flex;
  flex-wrap: wrap;
}

.con {
  flex-grow: 0;
  flex-shrink: 0;
  flex-basis: 100%;
}

@media only screen and (min-width: 769px){
  .con{ flex-basis: 50%; }
}

@media only screen and (min-width: 1024px){
  .con{ flex-basis: 25%; }
}

I've updated your pen here.