填充网格容器,以便始终填充最后一个网格项目区域

时间:2019-05-11 22:19:55

标签: css css3 css-grid grid-layout

现在我有一个网格,该网格具有 1行 5列,我将用于导航链接,但是在某些页面上还是有可能网格容器可能没有5个子代。

问题是网格从第一个可用区域开始填充。

是否可以用网格项填充网格容器,以便始终填充最后一个区域?

例如...

[a][b][c][d][ ] 应该是 [ ][a][b][c][d]

[a][b][c][ ][ ] 应该是 [ ][ ][a][b][c]

值得注意的是,我不想反转元素的方向,而是一直保持元素的顺序相同。

是否有简单的方法来实现无需修改列数?

1 个答案:

答案 0 :(得分:3)

由于只有5列,因此您可以使用nth-last-child()

为每个元素明确定义

.grid {
  display:grid;
  grid-template-columns:repeat(5,1fr);
  grid-gap:5px;
  margin:5px;
}
.grid > span {
  padding:10px;
  background:yellow;
  
}

.grid > span:nth-last-child(1) { grid-column:5; }
.grid > span:nth-last-child(2) { grid-column:4; }
.grid > span:nth-last-child(3) { grid-column:3; }
.grid > span:nth-last-child(4) { grid-column:2; }
/*.grid > span:nth-last-child(5) { grid-column:1; } this one is not needed*/
<div class="grid">
<span>a</span>
<span>b</span>
<span>c</span>
<span>d</span>
</div>

<div class="grid">
<span>a</span>
<span>b</span>
</div>

<div class="grid">
<span>a</span>
<span>b</span>
<span>c</span>
<span>d</span>
<span>e</span>
</div>

或者考虑在更容易的地方使用flexbox:

.grid {
  display:flex;
  margin:5px;
  justify-content:flex-end;
}
.grid > span {
  padding:10px;
  background:yellow;
  width:calc(20% - 10px);
  margin:5px;
  box-sizing:border-box;
}
<div class="grid">
<span>a</span>
<span>b</span>
<span>c</span>
<span>d</span>
</div>

<div class="grid">
<span>a</span>
<span>b</span>
</div>

<div class="grid">
<span>a</span>
<span>b</span>
<span>c</span>
<span>d</span>
<span>e</span>
</div>


关于CSS网格的另一个想法,其中的语法可以更直观,更容易地扩展到任意数量的列:

.grid {
  display:grid;
  grid-template-columns:repeat(var(--n,5),1fr);
  grid-gap:5px;
  margin:5px;
}
.grid > span {
  padding:10px;
  background:yellow;
  
}

.grid > span:nth-last-child(1) { grid-column-end:-1; }
.grid > span:nth-last-child(2) { grid-column-end:-2; }
.grid > span:nth-last-child(3) { grid-column-end:-3; }
.grid > span:nth-last-child(4) { grid-column-end:-4; }
.grid > span:nth-last-child(5) { grid-column-end:-5; }
.grid > span:nth-last-child(6) { grid-column-end:-6; }

/*.grid > span:nth-last-child(n) { grid-column-end:-n; }
  and so on ...
*/
<div class="grid">
<span>a</span>
<span>b</span>
<span>c</span>
</div>
<div class="grid" style="--n:4">
<span>a</span>
<span>b</span>
<span>c</span>
</div>

<div class="grid" style="--n:3">
<span>a</span>
<span>b</span>
</div>

<div class="grid" style="--n:6">
<span>a</span>
<span>b</span>
<span>c</span>
<span>d</span>
<span>e</span>
</div>