This question already has answers here:
Make grid container fill columns not rows
                                
                                    (5个答案)
                                
                        
                                在8个月前关闭。
            
                    
我有未知数量的项目需要在网格中显示。我想根据需要将列数设置为auto-fill,而行数没有限制。我可以正常工作:



.grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  list-style: none;
}

<ul class="grid">
  <li>a</li>
  <li>b</li>
  <li>c</li>
  <li>d</li>
  <li>e</li>
  <li>f</li>
  <li>g</li>
  <li>h</li>
</ul>





但是,我也希望这些项目按列的字母顺序排序:

a  d  g
b  e  h
c  f


我知道我可以使用grid-auto-flow: column按列而不是按行放置每个项目,但是如果这样做,我只会得到一个长行。



.grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  grid-auto-flow: column;
  list-style: none;
}

<ul class="grid">
  <li>a</li>
  <li>b</li>
  <li>c</li>
  <li>d</li>
  <li>e</li>
  <li>f</li>
  <li>g</li>
  <li>h</li>
</ul>





如何保留第一个代码段的行为,但从上到下而不是从左到右进行排序?

最佳答案

我认为做到这一点的唯一方法是考虑JS并动态调整行数。

这是一个简化的示例,如果您有间隙,填充等,则需要更完整的代码



var minv = 200;
var grid = document.querySelector('.grid');
var nb   = document.querySelectorAll('.grid li').length;

var nb_row = Math.ceil(nb/Math.floor(grid.offsetWidth/200));
/* grid.offsetWidth/200 = X will give the number of columns
   nb/X will give the number of rows

   We use floor with the first as we won't have overflow but a wrap (so 3.2 should be 3)
   We use ceil with the second one as we may have the last row with fewer elements (so 3.2 should be 4)

*/

grid.style.gridTemplateRows="repeat("+nb_row+",auto)";

window.addEventListener('resize', function(event){
   nb_row = Math.ceil(nb/Math.floor(grid.offsetWidth/200));
   grid.style.gridTemplateRows="repeat("+nb_row+",auto)";
});

.grid {
  display: grid;
  grid-auto-columns: minmax(200px, 1fr);
  grid-auto-flow: column;
  list-style: none;
  padding:0;
}

<ul class="grid">
  <li>a</li>
  <li>b</li>
  <li>c</li>
  <li>d</li>
  <li>e</li>
  <li>f</li>
  <li>g</li>
  <li>h</li>
</ul>

关于css - 我可以从上到下对网格元素进行排序,同时仍然包装到下一列吗? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55736919/

10-12 14:21