:has()用于查找奇数gird网格
.items {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 5vw;
}
@media (max-width: 800px) {
.items {
grid-template-columns: 1fr 1fr;
}
.items:has(.item:last-of-type:nth-of-type(odd)) .item:first-of-type {
grid-column: 1 / -1;
}
}
- 我们有一个
.items
. - 如果容器是其类型的最后
:has()
一个子容器,.item
- ……这
.item
恰好是一个奇数实例, - …然后选择该
.item
类型的第一个元素并为其设置样式!
利用 CSS Grid 的自动放置算法,我们甚至不必为网格显式声明固定数量的列和行——如果需要,CSS 会为我们创建它们!
html
<div class="controls">
<p>This grid sports a pattern that alternates by row and forces the last grid item to span all the columns if there is an odd number of grid items.</p>
<p>⚠️ Safari TP and Edge/Chrome Canary support at the moment.</p>
<button onclick="addItem()">Add Item</button>
<button onclick="removeItem()">Remove Item</button>
</div>
<div class="grid">
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</div>
css
.grid {
display: grid;
grid-auto-rows: 100px;
grid-auto-columns: 1fr;
grid-gap: 5px;
}
.grid :nth-child(4n + 1) {
grid-column: span 2;
}
.grid :nth-child(4n + 4) {
grid-column: 2 / span 2;
}
.grid:has(div:last-of-type:nth-of-type(odd)) div:last-of-type {
grid-column: 1 / 4;
}
/**/
.grid {
max-width: 600px;
margin: auto;
counter-reset: num;
}
.grid * {
border: 2px solid;
font-size: 30px;
box-sizing: border-box;
font-family: sans-serif;
display: grid;
place-content: center;
}
.grid *:before {
content: counter(num);
counter-increment: num;
}
/**/
.controls {
background: #fafafa;
font-family: Merriweather, serif;
line-height: 1.5;
margin: 1.35rem auto;
max-width: 55ch;
padding: 1.35rem;
}
摘自:https://css-tricks.com/implicit-grids-repeatable-layout-patterns-and-danglers/