Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keeping equal number of flex children per line when they wrap

Tags:

html

css

flexbox

I wonder how I could keep (approximately) the same amount of elements on every line, including the last one, with flex-wrap (or any other idea including flexbox).

For instance, I have a flexbox containing 6 elements. When it breaks I would like to have 3 elements on the first line, and 3 on the second (or both elements total width to be approximately the same).

(I don't want to resize the children, or to break flexbox functionalities.)

For now I just can get 5 elements on the first line, and one on the last line.

ul {
    display:flex;
    justify-content:space-between;
    flex-wrap:wrap;
}

Here is a jsfiddle : https://jsfiddle.net/yfj2g7wx/

I think most of the time it would give a better result graphically than wrapping elements one by one.

Is this possible ?

like image 698
kro Avatar asked Apr 08 '16 08:04

kro


2 Answers

You can use media queries to set the size of each flex item at certain breakpoints. So at the first breakpoint you would set flex-basis: 33%. This would force three items to a line.

@media screen and ( max-width: 900px ) {
  li { flex-basis: 33%; }                    /* forces three items to a line */
}

@media screen and ( max-width: 600px ) {
  li { flex-basis: 50%; }                    /* forces two items to a line */
}

@media screen and ( max-width: 300px ) {
  li { flex-basis: 100%; }                   /* forces one item per line line */
}

jsFiddle

like image 169
Michael Benjamin Avatar answered Sep 17 '22 14:09

Michael Benjamin


If you want an even amount of elements per row, then split them up and wrap two sets of three elements. Now you'll always get either a full 6 on one line, or 3 on 2 lines. It's also maintaining space-between on both lines which gives it that nice symmetrical look. I modified your Fiddle:

  • Wrapping the last 3 <li>s in a new <ul>.
  • Then wrapped a <section> around both <ul>s
  • Made the <section> a flex container.
  • Added flex to both <ul>s.

    section { display: flex; justify-content: space-between; flex-flow: row wrap; }

Fiddle

like image 42
zer00ne Avatar answered Sep 17 '22 14:09

zer00ne