如何实现 grid 布局顶部对齐?
各位好,我在用 grid 做一个页面的布局,请看代码
<div class="fruit-grid">
<div class="fruit">hello1</div>
<div class="fruit">hello2</div>
<div class="fruit">hello3</div>
<div class="fruit">hello4</div>
<div class="fruit">hello5</div>
<div class="fruit">hello6</div>
<div class="fruit">hello7</div>
</div>
我想实现的是一共分三列,最左边的一列是 hello1 和 hello2;中间是 3,4,5;最右侧是 6 和 7。 css 部分代码如下
.fruit-grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 10px;
align-items: start;
}
.fruit {
width: 100%;
margin-bottom: 10px;
}
/* 显示在最左 */
.fruit:nth-child(1),
.fruit:nth-child(2) {
grid-column: 1;
}
/* 显示在中间 */
.fruit:nth-child(3),
.fruit:nth-child(4),
.fruit:nth-child(5) {
grid-column: 2;
}
/* 显示在最右 */
.fruit:nth-child(6),
.fruit:nth-child(7) {
grid-column: 3;
}
现在遇到的问题是,中间和右侧的内容不顶部对齐,我想要的显示形式是
1 3 62 4 7 5
但实际的效果是
1
2 3
4
5 6
7
请问这个该怎么解决,谢谢。
如上问题所说,想知道错在哪里了
回复
1个回答

test
2024-06-23
你这个描述前后有点矛盾啊
最左边的一列是 hello1 和 hello2;中间是 3,4,5;最右侧是 6 和 7
现在遇到的问题是,中间和右侧的内容不顶部对齐,我想要的显示形式是
1 3 6
2 4 7
5
不应该是
1 3 6
2 4 7
5
在.fruit-grid
上添加grid-auto-flow: dense
就可以了,它会使元素尽可能的使用前面空的网格,而不是产生新的。
回复

适合作为回答的
- 经过验证的有效解决办法
- 自己的经验指引,对解决问题有帮助
- 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
- 询问内容细节或回复楼层
- 与题目无关的内容
- “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容