Initial problem
I have a flexbox on my page with boxy items that should be aligned in a grid in the center of the page. To achieve this, I used justify-content: center;
and it kind of worked but had one problem: if the last row of items wasn't a full row, instead of a grid-like structure the last row was misaligned.
My proposed solution
My solution to this problem would be to make the flexbox justify every item to the left, and take the width of it's contents like this: if 4 items can fit in a row with space remaining but 5 are too big, the flexbox becomes as wide as the 4 items (instead of 100% of its parent element), and then wraps to the next row. Now I can put this flexbox in an outer div
and set text-align: center;
for that.
How I tried to achieve my solution
So far I tried:
- using
display: inline-flex;
- using
width: fit-content;
andwidth: min-content;
- combining the last two points
- setting a max-width - didn't work because I won't know in advance how many items can fit and how wide they are
- use
display: grid;
withgrid-auto-flow: row;
instead of flex - this used the current.prodcategory
style but for some reason only displayed one item in a row and left most of the space empty. This also gives the same "one item a row" layout if thewidth: fit-content;
specification is removed from the container.
Current code
HTML/PHP (containers):
<div id='prodcontainer'>
<div id='prodcontainercenter'>
$productcategories
</div>
</div>
HTML/PHP (items, filled from an array):
$productcategories .= "<div class='prodcategory'>
<img src='$catimages[$i]'></img>
<span>$cattexts[$i]</span>
</div>";
CSS:
#prodcontainer
{
width: 100%;
text-align: center;
}
#prodcontainercenter
{
font-size: large;
width: fit-content;
display: inline-flex;
flex-wrap: wrap;
}
.prodcategory
{
/* this is so I can properly size
* some inner absolute pos elements*/
position: relative;
width: 20%;
margin: 1em 1em;
height: 25vh;
background-color: lightgreen;
}
Based on this information, how could I use either a grid or a flexbox to achieve my goal?