我正在尝试制作网格布局。网格中有 7 个项目。
我要显示的布局如下。
1 3 6
2 4 7
5
上面代码显示的实际布局是
1
2 3
4
5 6
7
我尝试为每个网格添加
self-align
,但它不起作用。如何解决这个问题?
.fruit-grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 10px;
align-items: start;
}
.fruit {
width: 100%;
margin-bottom: 10px;
}
/* left column */
.fruit:nth-child(1),
.fruit:nth-child(2) {
grid-column: 1;
}
/* middle column */
.fruit:nth-child(3),
.fruit:nth-child(4),
.fruit:nth-child(5) {
grid-column: 2;
}
/* right column */
.fruit:nth-child(6),
.fruit:nth-child(7) {
grid-column: 3;
}
<div class="fruit-grid">
<div class="fruit">1</div>
<div class="fruit">2</div>
<div class="fruit">3</div>
<div class="fruit">4</div>
<div class="fruit">5</div>
<div class="fruit">6</div>
<div class="fruit">7</div>
</div>
一个简单的方法是在这里使用
order
:
.fruit-grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 10px;
}
.fruit {
width: 100%;
margin-bottom: 10px;
}
/* left column */
.fruit:nth-child(1),
.fruit:nth-child(3),
.fruit:nth-child(6){
order: 1;
}
/* middle column */
.fruit:nth-child(2),
.fruit:nth-child(4),
.fruit:nth-child(7) {
order: 2;
}
/* right column */
.fruit:nth-child(5) {
order: 3;
}
<div class="fruit-grid">
<div class="fruit">1</div>
<div class="fruit">2</div>
<div class="fruit">3</div>
<div class="fruit">4</div>
<div class="fruit">5</div>
<div class="fruit">6</div>
<div class="fruit">7</div>
</div>
嗨,这是您完成任务所需的。希望这有帮助。
.grid-container {
display: grid;
grid-template-columns: repeat(3, 1fr); /* Creates 3 columns */
grid-auto-rows: minmax(50px, auto); /* Sets the minimum row height */
gap: 10px; /* Space between grid items */
}
.grid-item:nth-child(1) { grid-row: 1; grid-column: 1; }
.grid-item:nth-child(2) { grid-row: 2; grid-column: 1; }
.grid-item:nth-child(3) { grid-row: 1; grid-column: 2; }
.grid-item:nth-child(4) { grid-row: 2; grid-column: 2; }
.grid-item:nth-child(5) { grid-row: 3; grid-column: 1; }
.grid-item:nth-child(6) { grid-row: 1; grid-column: 3; }
.grid-item:nth-child(7) { grid-row: 2; grid-column: 3; }
<div class="grid-container">
<div class="grid-item">1</div>
<div class="grid-item">2</div>
<div class="grid-item">3</div>
<div class="grid-item">4</div>
<div class="grid-item">5</div>
<div class="grid-item">6</div>
<div class="grid-item">7</div>
</div>