I\'d like to implement a responsive grid-like layout using flexbox (without media queries). There can be variable number of elements in the grid. Each item should have fixed
One pretty straightforward solution is to just add a lot invisible, zero-height items at the end of your regular items:
<div class="parent">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
<div class="item">4</div>
<div class="dummyItem"></div>
<div class="dummyItem"></div>
<div class="dummyItem"></div>
<div class="dummyItem"></div>
</div>
and
.parent {
display: flex;
align-items: center;
justify-content: center;
flex-wrap: wrap;
}
.parent .item,
.parent .dummyItem{
width: 50px;
height: 50px;
background: white;
margin: 5px;
}
.parent .dummyItem {
height: 0;
}
If your longest row can have n
visible items, you'll need at least n-1
dummy items for this to work.
The only thing that's a little bit off with this is that if there's only one row then the items won't actually be centered; instead they'll be aligned (roughly) to the left.
Link to Codepen.