Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
447 views
in Technique[技术] by (71.8m points)

css - How to get grid items of different lengths to wrap?

With the repeat() and auto-fit / auto-fill functions it's easy to get grid items to wrap when there is a defined length pattern for the columns or rows.

In the example below, all columns are a minimum width of 100px and maximum width of 1fr.

jsFiddle demo

#grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
  grid-gap: 1em;
}

#grid > div {
  background-color: #ccddaa;
  padding: 10px;
}
<div id="grid">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Grid items do not actually wrap. The reason you see grid items "wrapping" to the next row is really because the explicit grid is being altered to keep within the constraints stipulated by minmax(). The number of columns generated by repeat() is proportional to the used width of the grid container, and the grid items are laid out one by one according to the number of columns, with new rows being created as necessary.

So, it is not possible to force the second grid item to wrap when there are two columns and there is room in the explicit grid to insert that grid item in the second column. Besides, even if you could tell the second grid item to "wrap", it would mean placing it in a new row in the first column, so its layout will be governed by the first column and not the second. Having it still be sized according to the second column would, of course, break the grid layout entirely.

If the intention is to accommodate smaller screens by wrapping elements to new lines, flex layout should be used, not grid layout. Grid layout is not suitable for this purpose.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...