
如何实现 grid 布局顶部对齐?
你在使用 grid 创建页面布局时遇到一个问题,即中间和右侧的内容没有顶部对齐,如下所示:
1
2 3
4
5 6
7
登录后复制
你想要的结果是:
1 3 6 2 4 7 5
登录后复制 登录后复制
代码如下:
<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>
登录后复制
.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;
}
登录后复制
解决这个问题的关键是添加 grid-auto-flow: dense 到 .fruit-grid。此属性使元素尽可能使用前面空的网格,而不是产生新的网格。
修改后的代码如下:
.fruit-grid {
...
grid-auto-flow: dense;
}
登录后复制
加了这条语句后,你的布局将以你想要的形式正确对齐:
1 3 6 2 4 7 5
登录后复制 登录后复制
以上就是如何使用 Grid 布局实现顶部对齐?的详细内容,更多请关注米云其它相关文章!
