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
but code was too much and not flexible and expandable.
Is it possible by flex? or grid?
* {
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;
}
p {
background: #ddd;
padding: 15px;
}
<div class="grid-wrapper">
<div class="grid-item">
<p>Grid Item</p>
</div>
<div class="grid-item">
<p>Grid Item</p>
</div>
<div class="grid-item">
<p>Grid Item</p>
</div>
<div class="grid-item">
<p>Grid Item</p>
</div>
<div class="grid-item">
<p>Grid Item</p>
</div>
<div class="grid-item">
<p>Grid Item</p>
</div>
<div class="grid-item">
<p>Grid Item</p>
</div>
<div class="grid-item">
<p>Grid Item</p>
</div>
<div class="grid-item">
<p>Grid Item</p>
</div>
<div class="grid-item">
<p>Grid Item</p>
</div>
</div>
You only need to consider one rule like below:
The trick is to make one element bigger to trigger the wrap then rely on
flex-grow
to fill the space.Full code
Here is a solution using grid which is easier to construct:
consider a 12-column grid layout using
grid-template-columns: repeat(12, 1fr)
,place each
grid-item
into 4 columns by usinggrid-column: span 3
,7
grid-item
s are repeating in a pattern; which means every even row has 3 items with nth-child indices7n
,7n - 1
and7n - 2
.See demo below:
Flexbox solution
And I'd use just about the same nth-child logic in the case of a flexbox and the only change in your code would be the below:
See demo below:
On a separate note, if you interested in having n items in a row with flexboxes, the below answers may give you more information: