3

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; and width: 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; with grid-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 the width: 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?

Community
  • 1
  • 1
sisisisi
  • 481
  • 7
  • 17
  • https://stackoverflow.com/q/42176419/3597276 – Michael Benjamin May 02 '20 at 00:46
  • 1
    CSS related question/issue, Don't put code from other technologies you might be using, it's irrelevant, You may add that code later only if asked, Now whoever is trying to help will have to start constructing the code to look at it the way you do, Try to put up a working snippet illustrating the issue with only the relevant parts – Rainbow May 02 '20 at 13:29

0 Answers0