2

I am using css flexbox to distribute a number of items in a container. I have a flex container like this:

.container{
    display: flex;
    flex-flow: row wrap;            
    align-content : center;
    justify-content : center;
    align-items : center;
}

When I add a certain number of fixed width/height items to the container they are placed as expected: if they don´t fit on a single flex-line the container creates a new one and some of the items are wrapped onto the next line. What I would like to do is have some control over the number of items that are displaced to the next line at he same time.

For example, if I place 9 items (that at first fit on one flex-line) and then I shrink the browser window, the container will first displace only the rightmost item to the next line, leaving 8 items on the first flex-line and only one on the second, what is not very aesthetically pleasant in my opinion. If I shrink the window more, I have a 7-2 distribution, and so on.

My question is, is there any way I can control how many items are displaced at once? My intent would be to have the number of items evenly distributed among the flex-lines, having the wider ones always on top, for any number of items.

For example, 9 items would be distributed this way:

  • When all items fit in a line: 1 flex-line: 9 items

  • When 9 items don´t fit jump to: 2 flex-lines: 5 items on the first line, 4 on the second.

  • When 5 items don´t fit in a line jump to: 3 flex-lines: 3-3-3

  • When 3 items don´t fit in a line jump to: 5 flex-lines: 2-2-2-2-1

Is there any way (maybe with the aid of jquery) to accomplish something like that? Any solution for a known number of elements would be appreciated, although my intent is to find one dynamically applicable to any number of items. Thanks!

Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
Rodrigo
  • 130
  • 2
  • 8

2 Answers2

1

What you're looking for is sometimes referred to as Quantity Queries.

If media queries allow for breakpoints based on viewport dimensions, quantity queries allow for breakpoints based on content quantity (e.g., sibling count).

It's not part of any official standard but I wouldn't call it a hack. The code can be quite elegant. It is a bit involved, however. Here you go:

Community
  • 1
  • 1
Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
0

Do you mean flex-basis?

.container .item {
    flex-basis: 25%;
}

It will divide to maximum 4 item per row.

Taufik Nur Rahmanda
  • 1,862
  • 2
  • 20
  • 36