创建按列流动的CSS网格,并根据内容创建动态列和行

编程入门 行业动态 更新时间:2024-10-28 18:26:07
本文介绍了创建按列流动的CSS网格,并根据内容创建动态列和行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有数量动态的元素(所有元素都相等)。我想将它们放置在网格中,以使它们按列排序,基于可用容器宽度的动态列数,以及基于元素数量的动态行数。

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网格,并根据内容创建动态列和行

本文发布于:2023-11-24 11:22:42,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1625005.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:网格   动态   内容   CSS

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!