'CSS Grid dynamiclly change the amout of rows and columns by the available space [duplicate]

I have a grid with a dynamic amount of items that need to be displayed inside the grid. So far so normal. Now I want the grid to automatically position all items in the grid. What I mean by this is the following:

  • If there is space for an additional item on the right, then create a new column and add it there
  • If this is not the case create a new row underneath and add the item in the first column of that row

I know the size of each item and all items have the same sizes. Currently, I defined the column size dynamically but if it would be required it would be okay to make all of them be the same (static) size.

.grid {
    display: grid;
    grid-auto-columns: minmax(360px, 460px);
    grid-auto-rows: 240px;
}

I tried using grid-auto-flow: column; but this made the items overflow out of the screen instead of moving them into a new row.

How can I make CSS determine the number of columns and rows needed dynamically? I know the size of each item so this should be no problem in my opinion

What I don't want to do is to use @media rules because then I would need to define like 50 rules for displays from 300px width to 16k displays. I also don't want to use JavaScript for this because that wouldn't be a great solution.



Solution 1:[1]

I think that CSS Flexbox will be more suitable for your case; you can image your grid as a one-directional container with elements that wraps on next line if there is no space to add them on the current line.

.container {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tamino