要想让 before 伪元素覆盖网格中所有列,可以将其应用于网格容器(grid container),并设置网格容器的 grid-template-columns 属性为 repeat(auto-fit, 1fr),这样每列宽度平均分配,并且自动适应容器宽度。
代码示例:
HTML:
CSS:
.grid-container {
display: grid;
grid-template-columns: repeat(auto-fit, 1fr);
position: relative;
}
.item:before {
content: "";
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.1);
z-index: -1;
}
在这个例子中,before 伪元素会被应用于每个项目(item)并将自己拉伸至整个网格容器的宽度和高度。由于网格容器的列宽度均分,before 伪元素的宽度也会自适应网格宽度,实现了覆盖所有列的效果。