有没有办法强制网格最后一行中的所有项目填充该行,无论它们有多少?
我不知道网格中的项目数量,因此无法直接定位它们。我尝试使用 grid-auto-flow:ensemble
,但它并没有真正帮助。
这是我的问题可视化: :
div { margin:20px auto; width: 400px; background: #d8d8d8; display: grid; grid-gap: 10px; grid-template-columns: repeat(3, 1fr); } span { height: 50px; background: blue; }
<div> <span></span> <span></span> <span></span> <span></span> <span></span> <span></span> <span></span> </div>
P粉4183516922023-10-21 11:05:17
通过结合 CSS 规则 nth-child 和 nth-last-of type,这对于 CSS 网格来说是完全可能的。唯一需要注意的是,需要提前知道列数。
.grid { display: grid; grid-template-columns: auto auto auto; justify-items: start; grid-gap: 10px; } .grid div { border: 1px solid #ccc; width: 100%; } .grid > *:nth-child(3n-1) { justify-self: center; text-align: center; } .grid > *:nth-child(3n) { justify-self: end; text-align: right; } .grid > *:nth-child(3n-1):nth-last-of-type(1) { border-color: red; grid-column: span 2; } .grid > *:nth-child(3n-2):nth-last-of-type(1) { border-color: red; grid-column: span 3; }
<div class="grid"> <div>text</div> <div>TEXT</div> <div>text</div> <div>text</div> <div>TEXT</div> <div>text</div> <div>text</div> <div>TEXT</div> </div>