Getting columns to wrap in CSS Grid

亡梦爱人 提交于 2019-11-29 09:34:35
Michael_B

Neither HTML or CSS have any concept of when descendants of a container wrap.

Essentially, the browser renders the document during an initial cascade. It does not reflow the document when a child wraps.

Therefore, to change the number of columns, you will need to set a width limit somewhere along the line or use media queries.

Here's a more in-depth explanation: Make container shrink-to-fit child elements as they wrap


If you can define a column width, then grid layout's auto-fill function makes wrapping easy.

In this example, the number of columns is based entirely on the width of the screen:

#grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(100px, 1fr)); /* see notes below */
  grid-gap: 1em;
}

#grid > div {
  background-color: #ccddaa;
}
<div id="grid">
  <div>text</div>
  <div>text</div>
  <div>text</div>
  <div>text</div>
  <div>text</div>
  <div>text</div>
  <div>text</div>
  <div>text</div>
  <div>text</div>
</div>

jsFiddle demo

Notes:

The auto-fill function allows the grid to line up as many grid tracks (columns or rows) as possible without overflowing the container. This can create similar behavior to flex layout's flex-wrap: wrap.

The minmax() function allows you to set a minimum and maximum size range for a grid track. In the code above, the width of column tracks will be a minimum of 100px and maximum of whatever free space is available.

The fr unit represents a fraction of the available space. It is similar to flex-grow in flex layout.

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