我有一个包含 16 个网格项的网格。
我希望第一行占用 4 个网格项,第二行 3,第三行 2 和第四行 7。我希望它们中的每一个都均匀分布,以便它们占据所有可用空间。
我可以在一定程度上通过在 中指定一个数字grid-template-columns
,即 12,并grid-column-end: span-*
在网格项目上使用来实现这一点。但是,这对于我希望 7 个项目均匀分布的行来说是不够的。
使用网格项目的预期行为grid-column-end
(除了最后一行有 7 个项目,其最后一项强制自己进入未在 中指定的行grid-template-columns
):
上面的代码片段:
.grid-container {
display: grid;
grid-template-columns: repeat(12, 1fr [col]);
grid-template-rows: repeat(4, 50px [row]);
grid-gap: 10px;
}
.grid-item {
border-radius: 5px;
color: white;
display: flex;
align-items: center;
justify-content: center;
}
.tier1 {
background-color: mediumseagreen;
grid-column-end: span 3;
}
.tier2 {
background-color: mediumorchid;
grid-column-end: span 4;
}
.tier3 {
background-color: mediumpurple;
grid-column-end: span 6;
}
.tier4 {
background-color: mediumvioletred;
grid-column-end: span 2;
}
<div class="grid-container">
<div class="grid-item tier1">1</div>
<div class="grid-item tier1">2</div>
<div class="grid-item tier1">3</div>
<div class="grid-item tier1">4</div>
<div class="grid-item tier2">5</div>
<div class="grid-item tier2">6</div>
<div class="grid-item tier2">7</div>
<div class="grid-item tier3">8</div>
<div class="grid-item tier3">9</div>
<div class="grid-item tier4">10</div>
<div class="grid-item tier4">11</div>
<div class="grid-item tier4">12</div>
<div class="grid-item tier4">13</div>
<div class="grid-item tier4">14</div>
<div class="grid-item tier4">15</div>
<div class="grid-item tier4">16</div>
</div>
我解决这个问题的想法是auto-fill
在grid-template-columns
属性中使用,但不解决单独的行。
自动填充行为:
.grid-container {
display: grid;
grid-template-columns: repeat(auto-fill, 50px);
grid-template-rows: repeat(4, 50px);
grid-gap: 10px;
}
.grid-item {
border-radius: 5px;
color: white;
display: flex;
align-items: center;
justify-content: center;
}
.tier1 {
background-color: mediumseagreen;
}
/* grid-column-end: span 3; */
.tier2 {
background-color: mediumorchid;
/* grid-column-end: span 4; */
}
.tier3 {
background-color: mediumpurple;
/* grid-column-end: span 6; */
}
.tier4 {
background-color: mediumvioletred;
/* grid-column-end: span 2; */
}
Code snippet of above:
<div class="grid-container">
<div class="grid-item tier1">1</div>
<div class="grid-item tier1">2</div>
<div class="grid-item tier1">3</div>
<div class="grid-item tier1">4</div>
<div class="grid-item tier2">5</div>
<div class="grid-item tier2">6</div>
<div class="grid-item tier2">7</div>
<div class="grid-item tier3">8</div>
<div class="grid-item tier3">9</div>
<div class="grid-item tier4">10</div>
<div class="grid-item tier4">11</div>
<div class="grid-item tier4">12</div>
<div class="grid-item tier4">13</div>
<div class="grid-item tier4">14</div>
<div class="grid-item tier4">15</div>
<div class="grid-item tier4">16</div>
</div>
CSS Grid 可以实现这样的行为吗?