我有数量动态的元素(所有元素都相等)。我想将它们放置在网格中,以使它们按列排序,基于可用容器宽度的动态列数,以及基于元素数量的动态行数。
I have a dynamic number of elements (all of equal dimensions). I want to position them in a grid, such that they are ordered in columns, with a dynamic number of columns based on the available container width, and with a dynamic number of rows based on the number of elements.
例如,假设有9个元素:
For example, assuming there are 9 elements:
1 4 7 2 5 8 3 6 9但是如果容器宽度扩大:
But if the container width expands:
1 3 5 7 9 2 4 6 8或缩小:
1 6 2 7 3 8 4 9 5放置物品时此方法很好按行,但不按列。另外,如果我显式设置行数,则可以很好地工作,但是,如果我对行和列都使用自动填充,则只会在一行中显示所有内容。
This works fine when the items are positioned by row, but not by column. Also, if I explicitly set the number of rows, it works fine, but if I use auto-fill for both rows and columns, it just displays everything in a single row.
这是一个简单的示例,我希望将其渲染为3x3网格: https:// codepen.io/anon/pen/ZxPQNd
Here's a simple example I would expect to be rendered as a 3x3 grid: codepen.io/anon/pen/ZxPQNd
#grid { width: 320px; border: 1px solid red; display: grid; grid-gap: 10px; grid-auto-flow: column; grid-template-rows: repeat(auto-fill, 100px); grid-template-columns: repeat(auto-fill, 100px); grid-auto-columns: 100px; grid-auto-rows: 100px; } #grid>div { background: lime; }
<div id="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>
推荐答案
使用CSS多列布局(使用 column-width 属性)可以实现所需的布局。演示:
Your desired layout is achievable using CSS multi-column layout using column-width property. Demo:
#grid { border: 1px solid red; column-width: 100px; column-gap: 10px; } #grid > div { break-inside: avoid-column; /* Prevent element from breaking */ page-break-inside: avoid; /* Prevent element from breaking in Firefox */ background: lime; width: 100px; height: 100px; margin-bottom: 10px; }
<div id="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>
更多推荐
创建按列流动的CSS网格,并根据内容创建动态列和行
发布评论