Make Grid Container Fill Columns Not Rows

Make grid items fill columns not rows

Initially, the grid lays out items in a horizontal direction. This is because an initial setting of a grid container is grid-auto-flow: row.

That's what you're getting in your layout:

.grid {  display: grid;  grid-template-columns: 1fr 1fr 1fr;  grid-auto-flow: row; /* default setting; can be omitted */}
<div class="grid">  <div>1</div>  <div>2</div>  <div>3</div>  <div>4</div>  <div>5</div>  <div>6</div>  <div>7</div>  <div>8</div>  <div>9</div></div>

CSS grid with auto-sized auto-filled rows

This requirement leads to contradictory scenarios:

Let's say there are 6 cells with the following lengths in that particular order:

11111, 2, 3, 44444, 5, 6

  • 3 columns → width: 7


    |11111|2|3|
    |44444|5|6|
  • 2 columns → width: 10


    |11111|2 |
    |3 |44444|
    |5 |6 |

⚠️ Reducing the number of columns for smaller screens would result in a wider grid in that case and it wouldn't fit any more.

This is at least one reason why the layout of such a grid could be a complex task, is not supported by CSS and why it is probably not a good idea in general.

Suggestions (CSS-only):

  • Manually define the number of columns for each screen size using media queries
  • or just use flex-wrap and make all cells the same width if they should align.

Grid that has uneven number of rows

To achieve this you need to use the grid-row-start css property on the last element and also will fix the repeat() since repeat() has 2 arguments to work correctly.

The repeat() function takes two arguments MDN documentation

.tableGrid {
display: grid;
grid-template-columns: 1fr 1fr;
grid-template-rows: repeat(5, 1fr); /* changed */
row-gap: 6px;
}

/* new style */
.tableGrid > div:nth-of-type(8) {
grid-row-start: 5;
}
<div class="tableGrid">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
<div>7</div>
<div>8</div>
</div>

CSS grid with fixed column size that adds extra columns to fill width of container

Here's my implementation:

The auto-fit argument with repeat CSS function