我有一个项目列表,按日期排序.
有些项目是未来的(绿色项目),因此更有趣,有些是过去(棕色项目).我希望第二组项目在新行中开始.
.grid{ width: 120px; display:grid; grid-template-columns: repeat(3,1fr); grid-gap: 10px; } .item{ border:1px solid black; height:50px; width:50px; } .green{ background:green; } .brown{ background:brown; }
<div class="grid"> <div class="item green"></div> <div class="item green"></div> <div class="item green"></div> <div class="item green"></div> <div class="item green"></div> <div class="item brown"></div> <div class="item brown"></div> <div class="item brown"></div> <div class="item brown"></div> </div>
每个类别的整体项目/项目数量不断变化,每行的项目数量取决于屏幕大小 – 这可能会消除一些可能的解决方案.
我当然可以在某个点拆分包含所有项目的数组,并将输出组织成两个单独的网格,如下所示:
.grid{ width: 120px; display:grid; grid-template-columns: repeat(3,1fr); grid-gap: 10px; margin-bottom:10px; } .item{ border:1px solid black; height:50px; width:50px; } .green{ background:green; } .brown{ background:brown; }
<div class="grid"> <div class="item green"></div> <div class="item green"></div> <div class="item green"></div> <div class="item green"></div> <div class="item green"></div> </div> <div class="grid"> <div class="item brown"></div> <div class="item brown"></div> <div class="item brown"></div> <div class="item brown"></div> </div>
可能这是最简单的选择.看起来像我想要实现的目标&做起来并不难.但无论如何,我很好奇:这有更优雅的方法吗?我想的是:
.item.green + .item.brown:before { /* force new row */ }
解决方法
你可以在.green之后定位第一个.brown并将
grid-column-start设置为1.
.grid { width: 120px; display: grid; grid-template-columns: repeat(3,1fr); grid-gap: 10px; } .item { border: 1px solid black; height: 50px; width: 50px; } .green { background: green; } .brown { background: brown; } .green + .brown { grid-column-start: 1; }
<div class="grid"> <div class="item green"></div> <div class="item green"></div> <div class="item green"></div> <div class="item green"></div> <div class="item green"></div> <div class="item brown"></div> <div class="item brown"></div> <div class="item brown"></div> <div class="item brown"></div> </div>