I want to show 4 items in 1st row as it is, but only 3 in second line, and then 4 in 3rd line and 3 in 4th line and so on...
I have achieved this by nth-child<
You only need to consider one rule like below:
/*7 = 4 (1st row) + 3 (2nd row) and 5 = 1st element in 2nd row (4 + 1)*/
.grid-wrapper .grid-item:nth-child(7n + 5) {
width: calc(100%/3);
flex-grow:0;
}
The trick is to make one element bigger to trigger the wrap then rely on flex-grow
to fill the space.
Full code
* {
box-sizing: border-box;
}
.grid-wrapper {
display: flex;
flex-wrap: wrap;
justify-content: center;
}
.grid-wrapper .grid-item {
width: 25%;
text-align: center;
padding: 5px;
flex-grow: 1;
}
.grid-wrapper .grid-item:nth-child(7n + 5) {
width: calc(100%/3);
flex-grow:0;
}
p {
background: #ffffd;
padding: 15px;
}
Grid Item
Grid Item
Grid Item
Grid Item
Grid Item
Grid Item
Grid Item
Grid Item
Grid Item
Grid Item
Grid Item
Grid Item
Grid Item
Grid Item
Grid Item
Grid Item
Grid Item
Grid Item
Grid Item
Grid Item
Grid Item