Is their an simple way in CSS to have a fixed maximum of child items on the same line, before you push the next child elements to a new line?
As i understand flexbox, child items only get pushed to a new line if their isint enough available space on the line above it. But i am seeking a CSS rule or function that let me say "i want a maximum of 3 child items on any given line, and even if space is available for a 4'th one push it to a new line".
For 3 items per row, add on the flex items: flex-basis: 33.333333% You can also use the flex 's shorthand like the following: flex: 0 0 33.333333% => which also means flex-basis: 33.333333% .
nowrap: The default value of wrap-flex is nowrap. It is used to specify that the item has no wrap. It makes item wrap in single lines.
One of the major drawbacks of using flexbox is performance issues. The use of flexbox can increase the page loading time if you have a larger project. You can compare the page loading time through Chrome development tools using the flexbox and the same pages constructed without using flexbox.
Use flex-basis.
.child {
flex-basis: 33%;
}
The percentage must be adapted according to you box-sizing model, and the use of margins and/or padding.
Or you could use CSS Grid for this:
Your HTML:
<div class="parent">
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
</div>
Your CSS:
.parent {
display: grid; // activate grid
grid-template-columns: repeat(4, 1fr); //make 4 cols with size 1fr
grid-gap: 20px; //gap between the rows
}
.child { //thats written with less. Just unnest for vanilla css
&:nth-child(3n+1) {
grid-column: 1;
}
&:nth-child(3n+2) {
grid-column: 2;
}
&:nth-child(3n+3) {
grid-column: 3;
}
&:nth-child(3n+4) {
grid-column: 1; //put the fourth item in a new row
}
}
I'm sure there are more efficient ways to write this with grid. But this does the job.
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