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?
Instead of using display: flex you could use float: left and clear every 3rd child node like this:
.child {
background: #000;
height: 300px;
float: left;
margin:15px 0 0 15px;
width:150px;
}
.child:nth-child(3n+1) {
clear: left;
}
I created a fiddle for you: fiddle example
In the case that the parent can hold only two children, you could use this short jQuery fix:
var child = $('.child'),
parent = $('.child').parent();
if( child.width() > (parent.width()/3) ) {
child.css('clear', 'none');
}
Fiddle with fix: fiddle example2
fiddle
#container {
display: flex;
flex-wrap: wrap;
justify-content: space-around;
}
#container>div {
margin: 15px;
width: 150px;
height: 150px;
}
/* negative paddings are treated as 0 so woohoo */
#container>div {
/* up to 3 boxes in a row */
padding: 0 calc((100% - 180px * 3) / 6);
}
#container>div {
/* up to 4 boxes in a row */
//padding: 0 calc((100% - 180px * 4) / 8);
}
#container>div {
/* up to 5 boxes in a row */
//padding: 0 calc((100% - 180px * 5) / 10);
}
/* 180px = width + horizontal margins */
You could place the items inside a container div that has a width of 100% and a max-width that is just enough to fit three items inside it?
.parent {
width:100%;
max-width:350px;
}
And then place this around all the items.
<div class="parent">
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
</div>
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.
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.
If you are using it with bootstrap you shoul add this css for pseudo row class
.row:before,
.row:after{
width:0 !important;
}