
如何实现 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 布局实现顶部对齐?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号