
如何解决使用 css grid 布局时内容不顶部对齐的问题?
问题描述:
在使用 css grid 布局创建一个三栏布局时,遇到中间和右侧内容不顶部对齐的情况,如下所示:
1
2 3
4
5 6
7而期望的显示形式应该是:
立即学习“前端免费学习笔记(深入)”;
1 3 6 2 4 7 5
原因分析:
原先的 css 代码中缺少了 grid-auto-flow: dense 属性。
解决方案:
在 fruit-grid 类上添加 grid-auto-flow: dense 属性,可以解决此问题。
.fruit-grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 10px;
align-items: start;
grid-auto-flow: dense;
}grid-auto-flow: dense 属性可让元素尽可能地使用前面空的网格,而不是创建新的网格行或列。从而实现顶部对齐。
修正后的代码:
hello1hello2hello3hello4hello5hello6hello7
.fruit-grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 10px;
align-items: start;
grid-auto-flow: dense;
}
.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;
}










