要实现瀑布流布局中让图片先排满第一行再排第二行,你可以使用 CSS 的多列布局(CSS multi-column layout)来控制。目前你的布局使用了 column-count 和 column-gap 来定义列数和列之间的间隙,但这会导致在不同列之间平均分布元素。
要实现你的需求,你可以考虑以下方法:
#grid-container 的 display 属性设置为 display: flex;,然后将子项 .item 添加到容器中。这样,子项将按照默认的 flex 行为依次排列,先排第一行再排第二行。示例代码如下:
在上面的示例中,我们使用 Flexbox 布局将子项按照你的要求排列。你可以根据需要进一步调整列数和间隙。
这两种方法都可以实现你的需求,你可以根据项目的具体要求选择其中之一。
案例:实现以下瀑布流布局,并且序号是先横向排列在换行排第二行

代码
- html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Documenttitle>
- head>
- <style>
- #grid-container {
- display: grid;
- grid-template-columns: repeat(2, 1fr); /* 定义三列网格 */
- grid-gap: 10px; /* 列之间和行之间的间隙 */
- width: 800px;
- border: 2px solid pink;
- }
-
- .item {
- margin-bottom: 10px; /* 行之间的间隙 */
- height: auto; /* 自动计算高度 */
- background-size: cover;
- background-position: center;
- text-align: center;
- }
-
- .item:nth-child(2n) {
- height: 12em;
- }
-
- .item:nth-child(3n) {
- height: 14em;
- }
-
- .item:nth-child(4n) {
- height: 16em;
- }
-
- .item:nth-child(5n) {
- height: 18em;
- }
-
- .item:nth-child(6n) {
- height: 20em;
- }
-
- .item:nth-child(7n) {
- height: 22em;
- }
-
- .item:nth-child(8n) {
- height: 24em;
- }
- style>
- <body>
- <div id="grid-container">
- div>
- body>
- <script>
- const gridContainer = document.getElementById('grid-container')
- for(let i=0;i<7;i++){
- const item = document.createElement('div');
- const textNode = document.createTextNode(`${i}`)
- item.appendChild(textNode)
- item.classList.add("item");
- item.style.backgroundImage = `url(https://picsum.photos/800/600?random=${i})`
- gridContainer.appendChild(item)
-
- }
- script>
- html>