有沒(méi)有辦法強(qiáng)制網(wǎng)格最後一行中的所有項(xiàng)目填入該行,無(wú)論它們有多少?
我不知道網(wǎng)格中的項(xiàng)目數(shù)量,因此無(wú)法直接定位它們。我嘗試使用 grid-auto-flow:ensemble
,但它並沒(méi)有真正幫助。
這是我的問(wèn)題視覺(jué)化: :
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>
透過(guò)結(jié)合 CSS 規(guī)則 nth-child 和 nth-last-of type,這對(duì)於 CSS 網(wǎng)格來(lái)說(shuō)是完全可能的。唯一要注意的是,需要事先知道列數(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>