I have a set of blocks with fixed dimensions that I want to arrange in a grid layout. Using flex-wrap: wrap
, I can distribute as many blocks as possible in each row. However, I need the entire wrapped column to be centered on the page, similar to this:
https://i.sstatic.net/szgrx.png
The issue is that in my current code snippet, the green flexbox expands to fill any available space, causing the blue boxes to align on the left side. I prefer not to set a fixed width for the flexbox so it can adjust to fit rows dynamically without occupying excess space.
While justify-content: center
can center the boxes within the container, it misaligns the incomplete row at the bottom, which is undesirable.
https://i.sstatic.net/mrIs0.png
Is there a CSS solution to achieve the desired effect?
I came across a suggestion in this thread mentioning the use of display: inline-flex
. While it works without wrapping, enabling flex-wrap: wrap
causes it to revert back to full-width filling behavior.
.page {
width: 100%;
background-color: pink;
padding: 10px;
box-sizing: border-box;
display: flex;
flex-direction: column;
align-items: center;
}
.flex-column {
display: flex;
flex-direction: row;
flex-wrap: wrap;
background-color: green;
justify-content: flex-start;
gap: 10px;
}
.flex-child {
display: block;
width: 200px;
height: 100px;
background-color: blue;
}
.button {
display: inline-block;
padding: 20px;
background-color: red;
}
.
<div class='page'>
<div class="flex-column">
<div class="flex-child"></div>
<div class="flex-child"></div>
<div class="flex-child"></div>
<div class="flex-child"></div>
<div class="flex-child"></div>
<div class="flex-child"></div>
<div class="flex-child"></div>
<div class="flex-child"></div>
</div>
<div class="button">Load more</div>
</div>