Make grid items fill columns not rows [duplicate]

回眸只為那壹抹淺笑 提交于 2019-11-26 17:21:25

问题


This question already has an answer here:

  • Make grid container fill columns not rows 5 answers

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>

回答1:


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



来源:https://stackoverflow.com/questions/47758544/make-grid-items-fill-columns-not-rows

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!