I have a flexbox. Its contents are NxN squares. I want the container to fit as many of these squares as possible given the display width. I want the flexbox to be center-aligned on the page.
However the problem is when I use
justify-content: center
image:
then the last row is not aligned to the left. However if I change to
justify-content: left
image:
then the entire container is no longer displayed center-aligned on the page. Can I somehow achieve a mix of two, so that is this example I would have centrally aligned 5 items, but the last row would be aligned to the first item in previous rows?
Minimal repro:
<style>
div { display: flex; flex-wrap: wrap; justify-content: center; }
i { display: block; width: 300px; height: 300px; background: black; margin: 10px; }
</style>
<div>
<i></i> <i></i> <i></i> <i></i> <i></i>
<i></i> <i></i> <i></i>
</div>
The layout you're building is a pretty standard grid. CSS grid is going to be a better fit than flexbox.
By using auto-fit
for the columns and setting each to a fixed size, it will fit as many columns as it can within the container. justify-content: center
will center your columns but content will still move across those columns from left to right.
Example:
div {
display: grid;
gap: 10px;
grid-template-columns: repeat(auto-fit, 160px);
justify-content: center;
}
span {
background: red;
display: block;
height: 160px;
}
<div>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With