我的整个网站有一个使用 12 列的网格布局 我想要 3 个项目,每个项目占用 3 列,并在它们之间分配重命名空间, 类似于 justify-content: space- Between 是 css flex
我知道我可以在没有CSS网格的情况下做到这一点,只是想知道是否
我可以用 CSS 网格做到这一点 我想要实现这样的目标
html
<div class="grid">
<div class="grid__item">1</div>
<div class="grid__item">2</div>
<div class="grid__item">3</div>
</div>
CSS
.grid {
display: grid;
grid-template-columns: repeat(12, 1fr);
width: 100%;
gap: 10px;
justify-content: space-between;
}
.grid__item {
grid-column: span 3;
}
.grid__item:nth-child(1) {
background: red;
}
.grid__item:nth-child(2) {
background: lightblue;
}
.grid__item:nth-child(3) {
background: lightgreen;
}
您必须计算 div 的宽度,然后将它们对齐到
grid-area
位置。
width: calc((100vw - (10px * 11))/4);
10px 是间隙,11 是基于列数的间隙数,4 是 12 除以元素数。
.grid {
display: grid;
grid-template-columns: repeat(12, 1fr);
grid-template-areas: "a a a b b b b b b c c c";
gap: 10px;
//justify-content: space-between;
}
.grid__item {
width: calc((100vw - (10px * 11))/4);
/* 10px is the gap, 11 is the number of gaps based on the number of columns, 4 is the 12 divided by the number of elements */
}
.grid__item:nth-child(1) {
background: red;
grid-area: a;
}
.grid__item:nth-child(2) {
background: lightblue;
grid-area: b;
justify-self: center;
}
.grid__item:nth-child(3) {
background: lightgreen;
grid-area: c;
}
<div class="grid">
<div class="grid__item">1</div>
<div class="grid__item">2</div>
<div class="grid__item">3</div>
</div>