7

I want my grid to fill in vertically:

1 4 7 
2 5 8
3 6 9

Instead of it fills in horizontally:

1 2 3
4 5 6
7 8 9

In my grid I want to specify the number of columns, not the number of rows.

This is what my div looks:

.grid {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
}
<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>
Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
Elvin Mammadov
  • 1,110
  • 7
  • 16

1 Answers1

11

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>

If you switch to grid-auto-flow: column, then the grid items are laid out vertically.

.grid {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  grid-auto-flow: column;
}
<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>

But for the row behavior in the vertical axis you need to define rows.

.grid {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  grid-auto-flow: column;
  grid-template-rows: 25px 25px 25px;
}
<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>

From the spec:

7.7. Automatic Placement: the grid-auto-flow property

This property controls how the auto-placement algorithm works, specifying exactly how auto-placed items get flowed into the grid.

row

The auto-placement algorithm places items by filling each row in turn, adding new rows as necessary. If neither row nor column is provided, row is assumed.

column

The auto-placement algorithm places items by filling each column in turn, adding new columns as necessary.

For an alternative solution to CSS Grid, which doesn't require specifying the number of rows, try CSS Columns: https://stackoverflow.com/a/44099977/3597276

Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701