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 ?
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 */
}
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:
<li>
s in a new <ul>
.<section>
around both <ul>
s<section>
a flex container.Added flex
to both <ul>
s.
section {
display: flex;
justify-content: space-between;
flex-flow: row wrap;
}
Fiddle
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