Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

html - Can I use css-grid to display an unknown number of items, in left-to-right reading order, over two rows?

I'd like to display a number of divs in left-to-right order, giving them an equal amount of space and spreading them over two rows.

e.g.

[div 1] | [div 2] | [div 3]
[div 4] | [div 5] | [div 6]

or

[div 1] | [div 2] | [div 3] | [div 4]
[div 5] | [div 6] | [div 7] | [div 8]

What's important is that I don't know how many elements there will be. If it's six, then I'll need three columns. If it's eight, then I'll need four columns. And so on.

If I give the grid container the following attributes:

  grid-auto-flow: column;
  grid-template-rows: repeat(2, 1fr);

Then my elements are given the right amount of space, but are displayed in the wrong order.

[div 1] | [div 3] | [div 5] | [div 7]
[div 2] | [div 4] | [div 6] | [div 8]

If I give the grid container the following attributes instead:

  grid-auto-flow: row;
  grid-template-rows: repeat(2, 1fr);

Then the elements appear in a single column.

[div 1]
[div 2]
...

Is there a simple way to display my elements across 2 rows, while maintaining left-to-right reading order, if I don't know how many elements there will be?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You will need javascript to calculate a min-width value for the grid column , then auto-fit,mimax() can do.

possible example

let yop =document.querySelectorAll('#test  div')
document.body.style.setProperty('--minWidth', Math.ceil(200 / yop.length) -1 +'%' );
#test {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(var(--minWidth), 1fr));
  counter-reset: divs;
  /* width:800px; or not */
}

div div  {
  border: solid;
  box-sizing:border-box;
}

div div:before {
  counter-increment: divs;
  content: counter(divs);
}
<div id="test">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div> 
  <div></div> 
</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...