有沒有辦法強制網(wǎng)格最后一行中的所有項目填充該行,無論它們有多少?
我不知道網(wǎng)格中的項目數(shù)量,因此無法直接定位它們。我嘗試使用 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>
通過結(jié)合 CSS 規(guī)則 nth-child 和 nth-last-of type,這對于 CSS 網(wǎng)格來說是完全可能的。唯一需要注意的是,需要提前知道列數(shù)。
.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>